package com.clickpaas.governmentcloud.service.policyservice.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bizcloud.ipaas.tb4093760b8224c4fbcff37d3fa266753.d20210207141638.codegen.TaccuratematchingApi;
import com.bizcloud.ipaas.tb4093760b8224c4fbcff37d3fa266753.d20210207141638.codegen.TenterprisesApi;
import com.bizcloud.ipaas.tb4093760b8224c4fbcff37d3fa266753.d20210207141638.codegen.TmatchingresultsApi;
import com.bizcloud.ipaas.tb4093760b8224c4fbcff37d3fa266753.d20210207141638.model.*;
import com.bizcloud.ipaas.tb4093760b8224c4fbcff37d3fa266753.d20210127152100.codegen.TpoliciesApi;
import com.bizcloud.ipaas.tb4093760b8224c4fbcff37d3fa266753.d20210127152100.model.TPoliciesDTO;
import com.bizcloud.ipaas.tb4093760b8224c4fbcff37d3fa266753.d20210127152100.model.TPoliciesDTOResponse;
import com.clickpaas.governmentcloud.common.ServerResponse;
import com.clickpaas.governmentcloud.common.TokenCommon;
import com.clickpaas.governmentcloud.entity.policyEntity.MatchingResults;
import com.clickpaas.governmentcloud.entity.policyEntity.PolicyEntity;
import com.clickpaas.governmentcloud.rules.hitech.HiTechRules;
import com.clickpaas.governmentcloud.service.exactmatchingservice.ExactMatchingService;
import com.clickpaas.governmentcloud.service.policyservice.PolicyService;
import com.clickpaas.governmentcloud.utils.dateutils.DateUtils;
import com.clickpaas.governmentcloud.utils.policycondcalutils.PolicyCondCal;
import com.clickpaas.governmentcloud.utils.portalutils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class PolicyServiceImpl implements PolicyService {

    @Autowired
    ExactMatchingService exactMatchingService;

    @Autowired
    TpoliciesApi tpoliciesApi;

    @Autowired
    TenterprisesApi tenterprisesApi;

    @Override
    public ServerResponse<?> matchHiTech(PolicyEntity policy) {
        ServerResponse<?> serverResponse = ServerResponse.createError("匹配失败");
        try {
            exactMatchingService.insertPolicy(policy);

            TmatchingresultsApi tmatchingresultsApi2 = new TmatchingresultsApi();
            TMatchingResultsDTO tMatchingResultsQuery2 = new TMatchingResultsDTO();
            tMatchingResultsQuery2.setUserInfo(policy.getCorpName());
            //tMatchingResultsQuery2.setatsandboxDBId(ConstantExt._SAND_BOX_ID);
            List<TMatchingResultsDTODelete> dataDel = new ArrayList<>();
            List<TMatchingResultsDTOResponse> data = tmatchingresultsApi2.findtMatchingResultsUsingPOST(tMatchingResultsQuery2).getData();
            if (data != null && data.size() > 0) {
                for (TMatchingResultsDTOResponse tMatchingResultsDTO1 : data) {
                    TMatchingResultsDTODelete tMatchingResultsDTO1Del = new TMatchingResultsDTODelete();
                    tMatchingResultsDTO1Del.setId(tMatchingResultsDTO1.getId());
                    //tMatchingResultsDTO1Del.setatsandboxDBId(ConstantExt._SAND_BOX_ID);
                    dataDel.add(tMatchingResultsDTO1Del);
                }
                String message = tmatchingresultsApi2.deletetMatchingResultsUsingPOST(dataDel).getMessage();
                System.out.println("公司名称: " + policy.getCorpName() + " 删除:" + message);
            }

            TpoliciesApi tpoliciesApi = new TpoliciesApi();
            // 所属行业
            List<String> industrys = policy.getIndustrys();
            // 是否违法
            String dishonesty = policy.getDishonesty();
            // 研发人员数
            Integer rOrDpersonnel = policy.getDpersonnel();
            // 职工总数
            Integer empTotal = policy.getEmpTotal();
            // 大前年研发费用
            Integer rOrDexpensesInTheYearBefore = policy.getDexpensesInTheYearBefore();
            // 前年研发费用
            Integer rOrDExpensesOfThePreviousYear = policy.getDexpensesOfThePreviousYear();
            // 去年研发费用
            Integer rOrDExpensesLastYear = policy.getDexpensesLastYear();
            // 大前年营业收入
            Integer yearBeforeTheUniversity = policy.getYearBeforeTheUniversity();
            // 前年营业收入
            Integer businessIncomeOfThePpreviousYear = policy.getBusinessIncomeOfThePpreviousYear();
            // 去年度营业收入
            Integer businessIncomeOfLastYear = policy.getBusinessIncomeOfLastYear();
            // 上年度高新产品
            Integer highTechProductsOfLastYear = policy.getHighTechProductsOfLastYear();
            // 发明专利数
            Integer inventionPatentsNumberOneClass = policy.getInventionPatentsNumberOneClass();
            // 集成电路数
            Integer integratedCircuitsOneClass = policy.getIntegratedCircuitsOneClass();
            // 实用新型专利数
            Integer utilityModelPatentsTwoClass = policy.getUtilityModelPatentsTwoClass();
            // 外观专利数
            Integer appearancePatentsTwoClass = policy.getAppearancePatentsTwoClass();
            // 软件著作权数
            Integer softwareCopyrightTwoClass = policy.getSoftwareCopyrightTwoClass();
            // 参与标准制定
            Integer participateDevelopment = policy.getParticipateDevelopment();
            // 科技成果转化
            Integer technologicalAchievements = policy.getTechnologicalAchievements();
            // 研发组织管理
            String formulateAndImproved = policy.getFormulatedAndImproved();
            // 产学研
            String researchInstitution = policy.getResearchInstitution();
            // 设备研发
            String researchAndDevelopmentSite = policy.getResearchAndDevelopmentSite();
            // 净资产增长率
            Integer growthRateOfNetAssets = policy.getGrowthRateOfNetAssets();
            // 专业化
            String industryTop10 = policy.getIndustryTop10();
            // 基本条件
            Integer registeredCapital = policy.getRegisteredCapital();
            // 资产总额
            Integer totalAssets = policy.getTotalAssets();
            // 市占率
            String marketShare = policy.getMarketShare();
            // 研发费用占比
            int rOrDProportionNum = 0;
            if (rOrDexpensesInTheYearBefore != null && rOrDExpensesOfThePreviousYear != null && rOrDExpensesLastYear != null && yearBeforeTheUniversity != null && businessIncomeOfThePpreviousYear != null && businessIncomeOfLastYear != null && (yearBeforeTheUniversity + businessIncomeOfThePpreviousYear + businessIncomeOfLastYear) != 0) {
                Integer aa = rOrDexpensesInTheYearBefore + rOrDExpensesOfThePreviousYear + rOrDExpensesLastYear;
                Integer bb = yearBeforeTheUniversity + businessIncomeOfThePpreviousYear + businessIncomeOfLastYear;
                float a = Float.parseFloat(aa.toString());
                float b = Float.parseFloat(bb.toString());
                float v = a / b * 100;
                rOrDProportionNum = Math.round(v);
            }
            // 特：品牌具有一定特色，获得过驰名商标、著名商标、名牌产品等荣誉称号（项）
            Integer brandCharacteristics = policy.getBrandCharacteristics();
            // 新：提供产品或服务满足“四新”经济发展特征，具有一定创新性，估值 （亿美元）
            String productOrService = policy.getProductOrService();
            BigDecimal productOrService2 = policy.getProductOrService2();
            // 用户信息
            String corpName = policy.getCorpName();

            // TODO 1.上海市高新技术企业认定 得分
            StringBuffer sb1 = new StringBuffer();
            // 注册时间
            String registeredTime = policy.getRegisteredTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
            Date startDate = new Date();
            String currTime = sdf.format(startDate);

            // 成立时间是否大于1年
            boolean establishmentTime = false;
            if (registeredTime != null) {
                establishmentTime = DateUtils.dayCompare(registeredTime, currTime, 365);
            }
            if (!establishmentTime) {
                sb1.append("成立年限不足1年，建议明年提交申请，并做好知识产权储备、研发辅助账、高新专项审计、产学研合作、研发组织管理等前期准备。\n");
            }

            // 是否包含高新技术领域
            boolean highTechField = HiTechRules.containHighTechField(industrys);
            // 是否存在违法行为
            boolean booleanDishonesty = false;
            if ("否".equals(dishonesty)) {
                booleanDishonesty = true;
            }
//
            // 科技人员占比 rOrDpersonnelRate
            boolean rOrDpersonnelRate = false;
            int rOrDpersonnelNum = 0;
            if (rOrDpersonnel != null && empTotal != null && empTotal != 0) {
                float a = Float.parseFloat(rOrDpersonnel.toString());
                float b = Float.parseFloat(empTotal.toString());
                float v = a / b * 100;
                rOrDpersonnelNum = Math.round(v);
            }
            if (rOrDpersonnelNum > 10) {
                rOrDpersonnelRate = true;
            }
            if (!rOrDpersonnelRate) {
                sb1.append("科技人员占比不足，建议聘用兼职和临时人员作为项目技术人员或辅助人员，并确保全年累计实际工作时间在183天以上。\n");
            }

            // 近3年研发费用占比
            boolean threeROrDRate = false;
            //大前年研发费用
            if ((businessIncomeOfLastYear <= 5000 && rOrDProportionNum >= 5) || (businessIncomeOfLastYear >= 5000 && businessIncomeOfLastYear <= 20000 && rOrDProportionNum >= 4) || (businessIncomeOfLastYear > 20000 && rOrDProportionNum >= 3)) {
                threeROrDRate = true;
            }
            if (!threeROrDRate) {
                sb1.append("研发费用占比不足，建议对公司硏发项目和高新技术产品进行系统规划和梳理，综合考虑企业的收入情况、研发人员情况、知识产权情况、技术情况、研发项目与产品的关联性情况等，确定合理的比例区间、RD数量、PS数量等。\n");
            }
            // 上年度高新产品和服务收入占比
            boolean booleanHighTechProduct = false;
            if (highTechProductsOfLastYear != null && businessIncomeOfLastYear != null && businessIncomeOfLastYear != 0) {
                float a = Float.parseFloat(highTechProductsOfLastYear.toString());
                float b = Float.parseFloat(businessIncomeOfLastYear.toString());
                float v = a / b * 100;

                int highTechProduct = Math.round(v);
                if (highTechProduct >= 60) {
                    booleanHighTechProduct = true;
                }
            }
            if (!booleanHighTechProduct) {
                sb1.append("高新产品（服务）收入不足，建议对公司专利技术和高新技术产品进行梳理，合理归集技术、研发项目与产品的关联性情况。\n");
            }
            TmatchingresultsApi tmatchingresultsApi = new TmatchingresultsApi();

            // 如果满足 "上海市高新技术企业认定" 政策必要条件，则计算分值，并匹配政策
            if (establishmentTime && highTechField && booleanDishonesty && rOrDpersonnelRate && threeROrDRate && booleanHighTechProduct) {
//            	if(true) {
                // 匹配政策
                TPoliciesDTO tPoliciesQuery = new TPoliciesDTO();
                tPoliciesQuery.setName("上海市高新技术企业认定");
                //tPoliciesQuery.setatsandboxDBId(ConstantExt._SAND_BOX_ID);
                List<TPoliciesDTOResponse> listPolicies = tpoliciesApi.findtPoliciesUsingPOST(tPoliciesQuery).getData();
                if (listPolicies != null && listPolicies.size() > 0) {
                    TPoliciesDTOResponse tPoliciesDTO1 = listPolicies.get(0);
                    // 政策ID
                    String policiesId = tPoliciesDTO1.getId();
                    // 政策名称
                    String policiesName = tPoliciesDTO1.getName();
                    // 申报条件
                    String condition = tPoliciesDTO1.getCondition();
                    // 申报入口
                    String url = tPoliciesDTO1.getEntrance();
                    // 主管部门
                    String competmentDepartment = tPoliciesDTO1.getCompetentDepartment();
                    // 申报日期
                    String startDateResult = tPoliciesDTO1.getStartDate();
                    if (startDateResult != null && !"".equals(startDateResult)) {
                        startDateResult = startDateResult.split(" ")[0];
                    }
                    String endDateResult = tPoliciesDTO1.getEndDate();
                    if (endDateResult != null && !"".equals(endDateResult)) {
                        endDateResult = endDateResult.split(" ")[0];
                    }
                    // 附件
                    List<Object> listAttachment = tPoliciesDTO1.getAttachment();

                    // 上海市高新技术企业认定 得分
                    Integer fraction = 0;

                    int oneClassNum = 0;
                    // 知识产权计算
                    if (inventionPatentsNumberOneClass != null && integratedCircuitsOneClass != null) {
                        oneClassNum = inventionPatentsNumberOneClass + integratedCircuitsOneClass;
                    }
                    if (utilityModelPatentsTwoClass != null && appearancePatentsTwoClass != null && softwareCopyrightTwoClass != null) {
                        int twoClassNum = utilityModelPatentsTwoClass + appearancePatentsTwoClass + softwareCopyrightTwoClass;
                        if (oneClassNum >= 1 && twoClassNum > 6) {
                            fraction += 27;
                        } else if (twoClassNum >= 6) {
                            fraction += 24;
                        } else if (twoClassNum >= 4) {
                            fraction += 18;
                        } else if (twoClassNum >= 3) {
                            fraction += 12;
                        } else if (twoClassNum >= 2) {
                            fraction += 6;
                        } else if (twoClassNum < 2) {
                            fraction += 0;
                        }
                        if (twoClassNum <= 4) {
                            sb1.append("知识产权数量偏少，请加强知识产权储备，建议申请软件著作权或实用新型专利，加快储备时间。\n");
                        }
                    }

                    // 参与标准制定
                    if (participateDevelopment != null) {
                        if (participateDevelopment > 0) {
                            fraction += 2;
                        }
                    }

                    // 科技成果转化
                    if (technologicalAchievements != null) {
                        if (technologicalAchievements >= 15) {
                            fraction += 27;
                        } else if (technologicalAchievements >= 12) {
                            fraction += 22;
                        } else if (technologicalAchievements >= 9) {
                            fraction += 16;
                        } else if (technologicalAchievements >= 6) {
                            fraction += 10;
                        } else if (technologicalAchievements >= 3) {
                            fraction += 5;
                        } else if (technologicalAchievements < 3) {
                            fraction += 0;
                        }
                        if (technologicalAchievements <= 9) {
                            sb1.append("科技成果转化数量偏少，建议结合自身知识产权情况，适当增加以技术成果形成的服务内容。\n");
                        }
                    }

                    // 研发组织管理
                    if ("是".equals(formulateAndImproved)) {
                        fraction += 12;
                    }
                    // 产学研
                    if ("是".equals(researchInstitution)) {
                        fraction += 2;
                    }
                    // 设备研发
                    if ("是".equals(researchAndDevelopmentSite)) {
                        fraction += 2;
                    }

                    // 净资产增长率
                    if (growthRateOfNetAssets != null) {
                        if (growthRateOfNetAssets >= 35) {
                            fraction += 10;
                        } else if (growthRateOfNetAssets >= 25) {
                            fraction += 8;
                        } else if (growthRateOfNetAssets >= 15) {
                            fraction += 6;
                        } else if (growthRateOfNetAssets >= 5) {
                            fraction += 4;
                        } else if (growthRateOfNetAssets >= 0) {
                            fraction += 2;
                        } else if (growthRateOfNetAssets <= 0) {
                            fraction += 0;
                        }
//                        if(growthRateOfNetAssets <= 15) {
//
//                        }
                    }


                    // 销售收入增长率(去年营业收入增长率)
                    if (businessIncomeOfThePpreviousYear != null && businessIncomeOfLastYear != null) {
                        if (businessIncomeOfThePpreviousYear != 0) {
                            Integer aa = businessIncomeOfLastYear - businessIncomeOfThePpreviousYear;
                            float a = Float.parseFloat(aa.toString());
                            float b = Float.parseFloat(businessIncomeOfThePpreviousYear.toString());
                            float v = a / b * 100;

                            int businessIncomeRate = Math.round(v);
                            if (businessIncomeRate >= 35) {
                                fraction += 10;
                            } else if (businessIncomeRate >= 25) {
                                fraction += 8;
                            } else if (businessIncomeRate >= 15) {
                                fraction += 6;
                            } else if (businessIncomeRate >= 5) {
                                fraction += 4;
                            } else if (businessIncomeRate >= 0) {
                                fraction += 2;
                            } else if (businessIncomeRate <= 0) {
                                fraction += 0;
                            }
                        }
                    }

                    if (sb1.length() == 0 && fraction >= 90) {
                        sb1.append("建议申报");
                    }

                    TMatchingResultsDTOQuery tMatchingResultsQuery = new TMatchingResultsDTOQuery();
                    TMatchingResultsDTOUpdate tMatchingResultsUpdate = new TMatchingResultsDTOUpdate();
                    tMatchingResultsUpdate.setName(policiesId);
                    tMatchingResultsUpdate.setPolicystring(policiesName);
                    tMatchingResultsUpdate.setApplicationCondition(condition);
                    tMatchingResultsUpdate.setCompetentDepartment(competmentDepartment);
                    tMatchingResultsUpdate.setStartdate(startDateResult);
                    tMatchingResultsUpdate.setEnddate(endDateResult);
                    tMatchingResultsUpdate.setNote(sb1.toString());
                    tMatchingResultsUpdate.setUrl(url);
                    tMatchingResultsUpdate.setApplicationDate(startDateResult + "-" + endDateResult);
                    tMatchingResultsUpdate.setAttachment(listAttachment);
                    tMatchingResultsUpdate.setMatchingDegree(new BigDecimal(fraction));
                    tMatchingResultsUpdate.setUserInfo(corpName);

                    SaveOrUpdatetMatchingResultsDTO saveOrUpdatetMatchingResultsDTO1 = new SaveOrUpdatetMatchingResultsDTO();
                    //tMatchingResultsUpdate.setatsandboxDBId(ConstantExt._SAND_BOX_ID);
                    saveOrUpdatetMatchingResultsDTO1.setQuery(tMatchingResultsQuery);
                    saveOrUpdatetMatchingResultsDTO1.setUpdate(tMatchingResultsUpdate);
                    String message = tmatchingresultsApi.saveOrUpdatetMatchingResultsUsingPOST(saveOrUpdatetMatchingResultsDTO1).getMessage();
                    System.out.println("上海市高新技术企业认定匹配结果: " + message);

                }
            } else {

//            	if(true) {
                // 匹配政策
                TPoliciesDTO tPoliciesQuery = new TPoliciesDTO();
                tPoliciesQuery.setName("上海市高新技术企业认定");
                //tPoliciesQuery.setatsandboxDBId(ConstantExt._SAND_BOX_ID);
                List<TPoliciesDTOResponse> listPolicies = tpoliciesApi.findtPoliciesUsingPOST(tPoliciesQuery).getData();
                if (listPolicies != null && listPolicies.size() > 0) {
                    TPoliciesDTOResponse tPoliciesDTO1 = listPolicies.get(0);
                    // 政策ID
                    String policiesId = tPoliciesDTO1.getId();
                    // 政策名称
                    String policiesName = tPoliciesDTO1.getName();
                    // 申报条件
                    String condition = tPoliciesDTO1.getCondition();
                    // 申报入口
                    String url = tPoliciesDTO1.getEntrance();
                    // 主管部门
                    String competmentDepartment = tPoliciesDTO1.getCompetentDepartment();
                    // 申报日期
                    String startDateResult = tPoliciesDTO1.getStartDate();
                    if (startDateResult != null && !"".equals(startDateResult)) {
                        startDateResult = startDateResult.split(" ")[0];
                    }
                    String endDateResult = tPoliciesDTO1.getEndDate();
                    if (endDateResult != null && !"".equals(endDateResult)) {
                        endDateResult = endDateResult.split(" ")[0];
                    }
                    // 附件
                    List<Object> listAttachment = tPoliciesDTO1.getAttachment();

                    // 上海市高新技术企业认定 得分
                    Integer fraction = 0;

                    int oneClassNum = 0;
                    // 知识产权计算
                    if (inventionPatentsNumberOneClass != null && integratedCircuitsOneClass != null) {
                        oneClassNum = inventionPatentsNumberOneClass + integratedCircuitsOneClass;
                    }
                    if (utilityModelPatentsTwoClass != null && appearancePatentsTwoClass != null && softwareCopyrightTwoClass != null) {
                        int twoClassNum = utilityModelPatentsTwoClass + appearancePatentsTwoClass + softwareCopyrightTwoClass;
                        if (oneClassNum >= 1 && twoClassNum > 6) {
                            fraction += 27;
                        } else if (twoClassNum >= 6) {
                            fraction += 24;
                        } else if (twoClassNum >= 4) {
                            fraction += 18;
                        } else if (twoClassNum >= 3) {
                            fraction += 12;
                        } else if (twoClassNum >= 2) {
                            fraction += 6;
                        } else if (twoClassNum < 2) {
                            fraction += 0;
                        }
                        if (twoClassNum <= 4) {
                            sb1.append("知识产权数量偏少，请加强知识产权储备，建议申请软件著作权或实用新型专利，加快储备时间。\n");
                        }
                    }

                    // 参与标准制定
                    if (participateDevelopment != null) {
                        if (participateDevelopment > 0) {
                            fraction += 2;
                        }
                    }

                    // 科技成果转化
                    if (technologicalAchievements != null) {
                        if (technologicalAchievements >= 15) {
                            fraction += 27;
                        } else if (technologicalAchievements >= 12) {
                            fraction += 22;
                        } else if (technologicalAchievements >= 9) {
                            fraction += 16;
                        } else if (technologicalAchievements >= 6) {
                            fraction += 10;
                        } else if (technologicalAchievements >= 3) {
                            fraction += 5;
                        } else if (technologicalAchievements < 3) {
                            fraction += 0;
                        }
                        if (technologicalAchievements <= 9) {
                            sb1.append("科技成果转化数量偏少，建议结合自身知识产权情况，适当增加以技术成果形成的服务内容。\n");
                        }
                    }

                    // 研发组织管理
                    if ("是".equals(formulateAndImproved)) {
                        fraction += 12;
                    }
                    // 产学研
                    if ("是".equals(researchInstitution)) {
                        fraction += 2;
                    }
                    // 设备研发
                    if ("是".equals(researchAndDevelopmentSite)) {
                        fraction += 2;
                    }

                    // 净资产增长率
                    if (growthRateOfNetAssets != null) {
                        if (growthRateOfNetAssets >= 35) {
                            fraction += 10;
                        } else if (growthRateOfNetAssets >= 25) {
                            fraction += 8;
                        } else if (growthRateOfNetAssets >= 15) {
                            fraction += 6;
                        } else if (growthRateOfNetAssets >= 5) {
                            fraction += 4;
                        } else if (growthRateOfNetAssets >= 0) {
                            fraction += 2;
                        } else if (growthRateOfNetAssets <= 0) {
                            fraction += 0;
                        }
//                        if(growthRateOfNetAssets <= 15) {
//
//                        }
                    }


                    // 销售收入增长率(去年营业收入增长率)
                    if (businessIncomeOfThePpreviousYear != null && businessIncomeOfLastYear != null) {
                        if (businessIncomeOfThePpreviousYear != 0) {
                            Integer aa = businessIncomeOfLastYear - businessIncomeOfThePpreviousYear;
                            float a = Float.parseFloat(aa.toString());
                            float b = Float.parseFloat(businessIncomeOfThePpreviousYear.toString());
                            float v = a / b * 100;

                            int businessIncomeRate = Math.round(v);
                            if (businessIncomeRate >= 35) {
                                fraction += 10;
                            } else if (businessIncomeRate >= 25) {
                                fraction += 8;
                            } else if (businessIncomeRate >= 15) {
                                fraction += 6;
                            } else if (businessIncomeRate >= 5) {
                                fraction += 4;
                            } else if (businessIncomeRate >= 0) {
                                fraction += 2;
                            } else if (businessIncomeRate <= 0) {
                                fraction += 0;
                            }
                        }
                    }

                    if (sb1.length() == 0 && fraction >= 90) {
                        sb1.append("建议申报");
                    }

                    TMatchingResultsDTOQuery tMatchingResultsQuery = new TMatchingResultsDTOQuery();
                    TMatchingResultsDTOUpdate tMatchingResultsUpdate = new TMatchingResultsDTOUpdate();
                    tMatchingResultsUpdate.setName(policiesId);
                    tMatchingResultsUpdate.setPolicystring(policiesName);
                    tMatchingResultsUpdate.setApplicationCondition(condition);
                    tMatchingResultsUpdate.setCompetentDepartment(competmentDepartment);
                    tMatchingResultsUpdate.setStartdate(startDateResult);
                    tMatchingResultsUpdate.setEnddate(endDateResult);
                    tMatchingResultsUpdate.setNote(sb1.toString());
                    tMatchingResultsUpdate.setUrl(url);
                    tMatchingResultsUpdate.setApplicationDate(startDateResult + "-" + endDateResult);
                    tMatchingResultsUpdate.setAttachment(listAttachment);
                    tMatchingResultsUpdate.setMatchingDegree(BigDecimal.ZERO);
                    tMatchingResultsUpdate.setUserInfo(corpName);

                    SaveOrUpdatetMatchingResultsDTO saveOrUpdatetMatchingResultsDTO1 = new SaveOrUpdatetMatchingResultsDTO();
                    //tMatchingResultsUpdate.setatsandboxDBId(ConstantExt._SAND_BOX_ID);
                    saveOrUpdatetMatchingResultsDTO1.setQuery(tMatchingResultsQuery);
                    saveOrUpdatetMatchingResultsDTO1.setUpdate(tMatchingResultsUpdate);
                    String message = tmatchingresultsApi.saveOrUpdatetMatchingResultsUsingPOST(saveOrUpdatetMatchingResultsDTO1).getMessage();
                    System.out.println("上海市高新技术企业认定匹配结果: " + message);

                }
//	    		if(!establishmentTime) {
//	    			System.out.println("成立时间不符");
//	    		}
//	    		if(!highTechField) {
//	    			System.out.println("是否包含高新技术领域");
//	    		}
//	    		if(!booleanDishonesty) {
//	    			System.out.println("是否存在违法行为");
//	    		}
                System.out.println("精确匹配: 上海市高新技术企业认定匹配 不满足必要条件");
//	    		System.out.println(establishmentTime && highTechField && booleanDishonesty && rOrDpersonnelRate && threeROrDRate && booleanHighTechProduct);
            }

            /**
             * 上海市专精特新中小企业认定
             */


            // 成立满两年
            boolean establishmentTime2 = false;
            if (registeredTime != null) {
                establishmentTime2 = DateUtils.dayCompare(registeredTime, currTime, 730);
            }
            int lastYeaer2 = 0;
            if (businessIncomeOfLastYear != null && businessIncomeOfThePpreviousYear != null && businessIncomeOfThePpreviousYear != 0) {
                // 前2年主营业务收入平均增长率
                float a = Float.parseFloat(businessIncomeOfLastYear.toString());
                float b = Float.parseFloat(businessIncomeOfThePpreviousYear.toString());
                float v = a / b;
                int round = Math.round(v);
                lastYeaer2 = (round ^ 1 / 2 - 1) * 100;
            }
            // 是否中小企业
            String enterpriseScale = policy.getEnterpriseScale();
            String copName = policy.getCorpName();
            /**
             * 专精特新增加对公司名称的判断
             */
            boolean isCopFlag = copName.contains("公司");
            // 进入逻辑
            if (establishmentTime2 && ("中型".equals(enterpriseScale) || "小微型".equals(enterpriseScale)) && isCopFlag) {

                // 匹配政策
                TPoliciesDTO tPoliciesQuery = new TPoliciesDTO();
                tPoliciesQuery.setName("上海市专精特新中小企业认定");
                //tPoliciesQuery.setatsandboxDBId(ConstantExt._SAND_BOX_ID);
                List<TPoliciesDTOResponse> listPolicies = tpoliciesApi.findtPoliciesUsingPOST(tPoliciesQuery).getData();
                if (listPolicies != null && listPolicies.size() > 0) {
                    TPoliciesDTOResponse tPoliciesDTO1 = listPolicies.get(0);
                    // 政策ID
                    String policiesId = tPoliciesDTO1.getId();
                    // 政策名称
                    String policiesName = tPoliciesDTO1.getName();
                    // 申报条件
                    String condition = tPoliciesDTO1.getCondition();
                    // 申报入口
                    String url = tPoliciesDTO1.getEntrance();
                    // 主管部门
                    String competmentDepartment = tPoliciesDTO1.getCompetentDepartment();
                    // 申报日期
                    String startDateResult = tPoliciesDTO1.getStartDate();
                    if (startDateResult != null && !"".equals(startDateResult)) {
                        startDateResult = startDateResult.split(" ")[0];
                    }
                    String endDateResult = tPoliciesDTO1.getEndDate();
                    if (endDateResult != null && !"".equals(endDateResult)) {
                        endDateResult = endDateResult.split(" ")[0];
                    }
                    // 附件
                    List<Object> listAttachment = tPoliciesDTO1.getAttachment();

                    // 上海市专精特新中小企业认定 得分
                    Integer fraction2 = 0;
                    // 基本条件
                    // 资本 1
                    if (registeredCapital != null) {
                        if (registeredCapital < 1000) {
                            fraction2 += 0;
                        } else {
                            fraction2 += 1;
                        }
                    }


                    // TODO 资本 2
                    if (totalAssets != null) {
                        if (totalAssets < 5000) {
                            fraction2 += 0;
                        } else {
                            fraction2 += 1;
                        }
                    }

                    // 营收 1
                    if (businessIncomeOfLastYear != null) {
                        if (businessIncomeOfLastYear < 5000) {
                            fraction2 += 0;
                        } else {
                            fraction2 += 3;
                        }
                    }

                    // 营收 2
                    // 前2年主营业务收入平均增长率
                    if (lastYeaer2 <= 10) {
                        fraction2 += 5;
                    } else if (lastYeaer2 > 10 && lastYeaer2 <= 20) {
                        fraction2 += 10;
                    } else if (lastYeaer2 > 20 && lastYeaer2 <= 50) {
                        fraction2 += 15;
                    } else if (lastYeaer2 > 50) {
                        fraction2 += 20;
                    }

                    // 基本条件得分总计
                    int baseFraction2 = fraction2;
                    int zhuan = 0, zhuan1 = 0, zhuan2 = 0;
                    // 专项条件 1
                    if ("国内前10".equals(industryTop10)) {
                        fraction2 += 20;
                        zhuan1 += 20;
                    } else if ("国内前3或者国际前10".equals(industryTop10)) {
                        fraction2 += 30;
                        zhuan1 += 30;
                    } else if ("国内第1或者国际前5".equals(industryTop10)) {
                        fraction2 += 40;
                        zhuan1 += 40;
                    }

                    // TODO 专项条件 2 待确认
                    if ("国内占有率50%以上或者国际占有率20%以上".equals(marketShare)) {
                        fraction2 += 10;
                        zhuan2 += 10;
                    } else if ("国内占有率30%-50%或者国际占有率10%-20%".equals(marketShare)) {
                        fraction2 += 20;
                        zhuan2 += 20;
                    }
                    zhuan = zhuan1 + zhuan2;
                    // 专精条件1 TODO
                    int jing = 0, jing1 = 0, jing2 = 0;
                    // 专精条件2
                    if (rOrDProportionNum >= 3 && rOrDProportionNum <= 5) {
                        fraction2 += 10;
                        jing2 += 10;
                    } else if (rOrDProportionNum > 5 && rOrDProportionNum <= 10) {
                        fraction2 += 15;
                        jing2 += 15;
                    } else if (rOrDProportionNum > 10) {
                        fraction2 += 20;
                        jing2 += 20;
                    }
                    jing = jing1 + jing2;

                    int te = 0, te1 = 0, te2 = 0;
                    // 特 1
                    if (participateDevelopment != null) {
                        if (participateDevelopment == 1) {
                            fraction2 += 10;
                            te1 += 10;
                        } else if (participateDevelopment >= 2 && participateDevelopment <= 5) {
                            fraction2 += 15;
                            te1 += 15;
                        } else if (participateDevelopment > 5) {
                            fraction2 += 20;
                            te1 += 20;
                        }
                    }

                    // 特 2
                    if (brandCharacteristics != null) {
                        if (brandCharacteristics == 1) {
                            fraction2 += 10;
                            te2 += 10;
                        } else if (brandCharacteristics == 2) {
                            fraction2 += 25;
                            te2 += 25;
                        } else if (brandCharacteristics > 2) {
                            fraction2 += 40;
                            te2 += 40;
                        }
                    }

                    te = te1 + te2;
                    // 新
                    int xin = 0;
                    BigDecimal yiyi = new BigDecimal(10000);
                    BigDecimal shiyi = new BigDecimal(100000);
                    if (productOrService != null && !"".equals(productOrService)) {
                        if (productOrService.contains("5G") || productOrService.contains("物联网") || productOrService.contains("人工智能") || productOrService.contains("AI") || productOrService.contains("大数据") || productOrService.contains("区块链") || productOrService.contains("生物医药")) {
                            fraction2 += 25;
                            xin += 25;
                        } else if (productOrService2 != null && productOrService2.compareTo(yiyi) > -1 && productOrService2.compareTo(shiyi) < 1) {
                            fraction2 += 40;
                            xin += 40;
                        } else if (productOrService2 != null && productOrService2.compareTo(shiyi) > -1) {
                            fraction2 += 54;
                            xin += 54;
                        }
                    }

                    List<Integer> ListMaxScore = new ArrayList<>();
                    ListMaxScore.add(zhuan);
                    ListMaxScore.add(jing);
                    ListMaxScore.add(te);
                    ListMaxScore.add(xin);

                    // 专项特新 最高分
                    Integer maxScore = Collections.max(ListMaxScore);
                    // 专家判断
                    Integer defindeScore = 8;
                    fraction2 += defindeScore;

                    TMatchingResultsDTOQuery tMatchingResultsQuery = new TMatchingResultsDTOQuery();
//		    		tMatchingResultsQuery.setUserInfo(corpName);
                    TMatchingResultsDTOUpdate tMatchingResultsUpdate = new TMatchingResultsDTOUpdate();
                    tMatchingResultsUpdate.setName(policiesId);
                    tMatchingResultsUpdate.setPolicystring(policiesName);
                    tMatchingResultsUpdate.setApplicationCondition(condition);
                    tMatchingResultsUpdate.setCompetentDepartment(competmentDepartment);
                    tMatchingResultsUpdate.setStartdate(startDateResult);
                    tMatchingResultsUpdate.setEnddate(endDateResult);
                    tMatchingResultsUpdate.setUrl(url);
                    tMatchingResultsUpdate.setApplicationDate(startDateResult + "-" + endDateResult);
                    tMatchingResultsUpdate.setAttachment(listAttachment);
                    tMatchingResultsUpdate.setMatchingDegree(new BigDecimal(fraction2));
                    tMatchingResultsUpdate.setUserInfo(corpName);

                    SaveOrUpdatetMatchingResultsDTO saveOrUpdatetMatchingResultsDTO1 = new SaveOrUpdatetMatchingResultsDTO();
                    //tMatchingResultsUpdate.setatsandboxDBId(ConstantExt._SAND_BOX_ID);
                    saveOrUpdatetMatchingResultsDTO1.setQuery(tMatchingResultsQuery);
                    saveOrUpdatetMatchingResultsDTO1.setUpdate(tMatchingResultsUpdate);
                    String message = tmatchingresultsApi.saveOrUpdatetMatchingResultsUsingPOST(saveOrUpdatetMatchingResultsDTO1).getMessage();
                    System.out.println("上海市专精特新中小企业认定匹配结果: " + message);

                }

            } else {
                System.out.println("精确匹配: 上海市专精特新中小企业认定匹配 不满足必要条件");
            }

            /**
             * 上海市高新技术企业入库培训
             */
            // 成立时间是否大于1年
            boolean establishmentTime3 = DateUtils.dayCompare(registeredTime, currTime, 365);
//	    	if(!establishmentTime3) {
//	    		serverResponse = ServerResponse.createError("成立时间小于1年");
//	    	}
            // 是否包含高新技术领域
            boolean highTechField3 = HiTechRules.containHighTechField3(industrys);
//	    	if(!highTechField3) {
//	    		serverResponse = ServerResponse.createError("不包含高新技术领域");
//	    	}
            // 是否存在违法行为
            boolean booleanDishonesty3 = false;
            if ("否".equals(dishonesty)) {
                booleanDishonesty3 = true;
            }

            // 科技人员占比 rOrDpersonnelRate
            boolean rOrDpersonnelRate3 = false;
            if (rOrDpersonnel != null && empTotal != null && empTotal != 0) {
                float a = Float.parseFloat(rOrDpersonnel.toString());
                float b = Float.parseFloat(empTotal.toString());
                float v = a / b * 100;
                int rOrDpersonnelNum3 = Math.round(v);
                if (rOrDpersonnelNum3 > 5) {
                    rOrDpersonnelRate3 = true;
                }
            }

            // 近3年研发费用占比
            boolean threeROrDRate3 = false;
            if (yearBeforeTheUniversity != null && businessIncomeOfThePpreviousYear != null && businessIncomeOfLastYear != null) {
                if (yearBeforeTheUniversity + businessIncomeOfThePpreviousYear + businessIncomeOfLastYear != 0) {
                    //大前年研发费用
                    if (rOrDexpensesInTheYearBefore != null && rOrDExpensesOfThePreviousYear != null && rOrDExpensesLastYear != null) {
                        Integer aa = rOrDexpensesInTheYearBefore + rOrDExpensesOfThePreviousYear + rOrDExpensesLastYear;
                        Integer bb = yearBeforeTheUniversity + businessIncomeOfThePpreviousYear + businessIncomeOfLastYear;
                        float a = Float.parseFloat(aa.toString());
                        float b = Float.parseFloat(bb.toString());
                        float v = a / b * 100;
                        int rOrDProportionNum3 = Math.round(v);
                        if (rOrDProportionNum3 >= 3) {
                            threeROrDRate3 = true;
                        }
                    }
                }
            }

            // 上年度高新产品和服务收入占比
            boolean booleanHighTechProduct3 = false;
            if (highTechProductsOfLastYear != null && businessIncomeOfLastYear != null && businessIncomeOfLastYear != 0) {
                float a = Float.parseFloat(highTechProductsOfLastYear.toString());
                float b = Float.parseFloat(businessIncomeOfLastYear.toString());
                float v = a / b * 100;
                int highTechProduct3 = Math.round(v);
                if (highTechProduct3 >= 40) {
                    booleanHighTechProduct3 = true;
                }
            }

            if (establishmentTime3 && highTechField3 && booleanDishonesty3 && rOrDpersonnelRate3 && threeROrDRate3 && booleanHighTechProduct3) {
                // 匹配政策
                TPoliciesDTO tPoliciesQuery = new TPoliciesDTO();
                tPoliciesQuery.setName("上海市高新技术企业入库培训");
                //tPoliciesQuery.setatsandboxDBId(ConstantExt._SAND_BOX_ID);
                List<TPoliciesDTOResponse> listPolicies = tpoliciesApi.findtPoliciesUsingPOST(tPoliciesQuery).getData();
                if (listPolicies != null && listPolicies.size() > 0) {
                    TPoliciesDTOResponse tPoliciesDTO1 = listPolicies.get(0);
                    // 政策ID
                    String policiesId = tPoliciesDTO1.getId();
                    // 政策名称
                    String policiesName = tPoliciesDTO1.getName();
                    // 申报条件
                    String condition = tPoliciesDTO1.getCondition();
                    // 申报入口
                    String url = tPoliciesDTO1.getEntrance();
                    // 主管部门
                    String competmentDepartment = tPoliciesDTO1.getCompetentDepartment();
                    // 申报日期
                    String startDateResult = tPoliciesDTO1.getStartDate();
                    if (startDateResult != null && !"".equals(startDateResult)) {
                        startDateResult = startDateResult.split(" ")[0];
                    }
                    String endDateResult = tPoliciesDTO1.getEndDate();
                    if (endDateResult != null && !"".equals(endDateResult)) {
                        endDateResult = endDateResult.split(" ")[0];
                    }
                    // 附件
                    List<Object> listAttachment = tPoliciesDTO1.getAttachment();

                    // 上海市高新技术企业入库培训 得分
                    Integer fraction = 0;


                    // 知识产权计算
                    int oneClassNum = 0;
                    if (inventionPatentsNumberOneClass != null && integratedCircuitsOneClass != null) {
                        oneClassNum = inventionPatentsNumberOneClass + integratedCircuitsOneClass;
                    }
                    if (utilityModelPatentsTwoClass != null && appearancePatentsTwoClass != null && softwareCopyrightTwoClass != null) {
                        int twoClassNum = utilityModelPatentsTwoClass + appearancePatentsTwoClass + softwareCopyrightTwoClass;
                        if (oneClassNum >= 1 && twoClassNum > 6) {
                            fraction += 27;
                        } else if (twoClassNum >= 6) {
                            fraction += 24;
                        } else if (twoClassNum >= 4) {
                            fraction += 18;
                        } else if (twoClassNum >= 3) {
                            fraction += 12;
                        } else if (twoClassNum >= 2) {
                            fraction += 6;
                        } else if (twoClassNum < 2) {
                            fraction += 0;
                        }
                    }


                    // 参与标准制定
                    if (participateDevelopment != null) {
                        if (participateDevelopment > 0) {
                            fraction += 2;
                        }
                    }

                    // 科技成果转化
                    if (technologicalAchievements != null) {
                        if (technologicalAchievements >= 15) {
                            fraction += 27;
                        } else if (technologicalAchievements >= 12) {
                            fraction += 22;
                        } else if (technologicalAchievements >= 9) {
                            fraction += 16;
                        } else if (technologicalAchievements >= 6) {
                            fraction += 10;
                        } else if (technologicalAchievements >= 3) {
                            fraction += 5;
                        } else if (technologicalAchievements < 3) {
                            fraction += 0;
                        }
                    }

                    // 研发组织管理
                    if ("是".equals(formulateAndImproved)) {
                        fraction += 12;
                    }
                    // 产学研
                    if ("是".equals(researchInstitution)) {
                        fraction += 2;
                    }
                    // 设备研发
                    if ("是".equals(researchAndDevelopmentSite)) {
                        fraction += 2;
                    }

                    // 净资产增长率
                    if (growthRateOfNetAssets != null) {
                        if (growthRateOfNetAssets >= 35) {
                            fraction += 10;
                        } else if (growthRateOfNetAssets >= 25) {
                            fraction += 8;
                        } else if (growthRateOfNetAssets >= 15) {
                            fraction += 6;
                        } else if (growthRateOfNetAssets >= 5) {
                            fraction += 4;
                        } else if (growthRateOfNetAssets >= 0) {
                            fraction += 2;
                        } else if (growthRateOfNetAssets <= 0) {
                            fraction += 0;
                        }
                    }


                    // 销售收入增长率(去年营业收入增长率)
                    if (businessIncomeOfLastYear != null && businessIncomeOfThePpreviousYear != null && businessIncomeOfThePpreviousYear != 0) {
                        Integer aa = businessIncomeOfLastYear - businessIncomeOfThePpreviousYear;
                        float a = Float.parseFloat(aa.toString());
                        float b = Float.parseFloat(businessIncomeOfThePpreviousYear.toString());
                        float v = a / b * 100;
                        int businessIncomeRate = Math.round(v);
                        if (businessIncomeRate >= 35) {
                            fraction += 10;
                        } else if (businessIncomeRate >= 25) {
                            fraction += 8;
                        } else if (businessIncomeRate >= 15) {
                            fraction += 6;
                        } else if (businessIncomeRate >= 5) {
                            fraction += 4;
                        } else if (businessIncomeRate >= 0) {
                            fraction += 2;
                        } else if (businessIncomeRate <= 0) {
                            fraction += 0;
                        }
                    }

                    TMatchingResultsDTOQuery tMatchingResultsQuery = new TMatchingResultsDTOQuery();
                    TMatchingResultsDTOUpdate tMatchingResultsUpdate = new TMatchingResultsDTOUpdate();
                    tMatchingResultsUpdate.setName(policiesId);
                    tMatchingResultsUpdate.setPolicystring(policiesName);
                    tMatchingResultsUpdate.setApplicationCondition(condition);
                    tMatchingResultsUpdate.setCompetentDepartment(competmentDepartment);
                    tMatchingResultsUpdate.setStartdate(startDateResult);
                    tMatchingResultsUpdate.setEnddate(endDateResult);
                    tMatchingResultsUpdate.setUrl(url);
                    tMatchingResultsUpdate.setApplicationDate(startDateResult + "-" + endDateResult);
                    tMatchingResultsUpdate.setAttachment(listAttachment);
                    tMatchingResultsUpdate.setMatchingDegree(new BigDecimal(fraction));
                    tMatchingResultsUpdate.setUserInfo(corpName);

                    SaveOrUpdatetMatchingResultsDTO saveOrUpdatetMatchingResultsDTO1 = new SaveOrUpdatetMatchingResultsDTO();
                    //tMatchingResultsUpdate.setatsandboxDBId(ConstantExt._SAND_BOX_ID);
                    saveOrUpdatetMatchingResultsDTO1.setQuery(tMatchingResultsQuery);
                    saveOrUpdatetMatchingResultsDTO1.setUpdate(tMatchingResultsUpdate);
                    String message = tmatchingresultsApi.saveOrUpdatetMatchingResultsUsingPOST(saveOrUpdatetMatchingResultsDTO1).getMessage();
                    System.out.println("上海市高新技术企业入库培训匹配结果: " + message);


                }


            } else {
                System.out.println("精确匹配: 上海市高新技术企业入库培训匹配 不满足必要条件");
            }

            serverResponse = ServerResponse.createSuccess("匹配成功");


        } catch (Exception e) {
            e.printStackTrace();
        }


        return serverResponse;
    }

//    @Override
//    public ServerResponse<?> searchMatchingResult(Integer pageNum, Integer pageSize, String policiesName, String corpName) {
//        ServerResponse<?> serverResponse = ServerResponse.createError("查询失败");
//        try {
//
//            List<MatchingResults> listMatchResult = new ArrayList<>();
//            String total = "0";
//            List<String> ids = new ArrayList<>();
//            if (policiesName != null && !"".equals(policiesName)) {
//                TpoliciesApi tpoliciesApi = new TpoliciesApi();
//                TPoliciesDTO1 tPoliciesDTO1 = new TPoliciesDTO1();
//                tPoliciesDTO1.setatlikeQueryField("name");
//                tPoliciesDTO1.setName(policiesName);
//                List<TPoliciesDTO1> listPolicies = tpoliciesApi.findtPoliciesUsingPOST(tPoliciesDTO1, null).getData();
//                if (listPolicies != null && listPolicies.size() > 0) {
//                    ids = listPolicies.stream().map(p -> {
//                        return p.getId();
//                    }).collect(Collectors.toList());
//
//                }
//            }
//
//            TmatchingresultsApi tmatchingresultsApi = new TmatchingresultsApi();
//            TMatchingResultsDTOPageInfo tMatchingResultsDTOPageInfo = new TMatchingResultsDTOPageInfo();
//            tMatchingResultsDTOPageInfo.setatsdkpageNum(String.valueOf(pageNum));
//            tMatchingResultsDTOPageInfo.setatsdkpageSize(String.valueOf(pageSize));
//            tMatchingResultsDTOPageInfo.setUserInfo(corpName);
//            if (ids != null && ids.size() > 0) {
//                tMatchingResultsDTOPageInfo.setatmultiValueField("policy");
//                tMatchingResultsDTOPageInfo.setPolicy(listToString(ids));
//            }
//
//            DataResponsetMatchingResultsDTOPageInfodata dataResponse = tmatchingresultsApi.findPageInfotMatchingResultsUsingPOST(tMatchingResultsDTOPageInfo, null).getData();
//            if (dataResponse != null) {
//                total = dataResponse.getTotal();
//
//                if (total == null) {
//                    total = "0";
//                } else {
//                    List<TMatchingResultsDTO1> listMatchingResult = dataResponse.getDataList();
//                    if (listMatchingResult != null && listMatchingResult.size() > 0) {
//                        for (TMatchingResultsDTO1 tMatchingResultsDTO1 : listMatchingResult) {
//                            String policyName = (String) tMatchingResultsDTO1.getPolicy();
//                            String applicationCondition = tMatchingResultsDTO1.getApplicationCondition();
//                            String competmentDepartment = tMatchingResultsDTO1.getCompetentDepartment();
//                            if (competmentDepartment != null && !"".equals(competmentDepartment)) {
//                                Object parse = JSONObject.parse(competmentDepartment);
//                                JSONObject parseObject = JSONObject.parseObject(parse.toString());
//                                competmentDepartment = parseObject.getString("name");
//                            }
//                            String applicationDate = tMatchingResultsDTO1.getApplicationDate();
//                            String attachment = null;
//                            String filePath = "";
//                            String fileName = "";
//                            List<Object> listAttachment = tMatchingResultsDTO1.getAttachment();
//                            if (listAttachment != null && listAttachment.size() > 0) {
//                                attachment = (String) listAttachment.get(0);
//                                JSONObject parseObject = JSONObject.parseObject(attachment);
//                                filePath = parseObject.getString("filePath");
//                                fileName = parseObject.getString("fileName");
//                                if (fileName != null && !"".equals(fileName)) {
//                                    if (fileName.substring(0).equals("“")) {
//                                        fileName = fileName.replaceAll("“", "");
//                                    }
//                                }
//
//                            }
//                            BigDecimal matchingDegree = tMatchingResultsDTO1.getMatchingDegree();
//
//                            MatchingResults matchingResults = new MatchingResults();
//                            matchingResults.setPolicyName(policyName);
//                            matchingResults.setDeclarationConditions(applicationCondition);
//                            matchingResults.setCompetentDepartment(competmentDepartment);
//                            matchingResults.setDeclarationTime(applicationDate);
//                            matchingResults.setAttachmentName(fileName);
//                            matchingResults.setAttachmentUrl(filePath);
//                            matchingResults.setScore(matchingDegree.intValue());
//                            listMatchResult.add(matchingResults);
//                        }
//                    }
//                }
//            }
//
//            //插入代码-如下
//            List<MatchingResults> matchingResultsListByCorpName = matchingResultsListByCorpName(corpName);
//
//            if (matchingResultsListByCorpName.size() > 0 && listMatchResult.size() > 0) {
//                List<Integer> oldIndex = new ArrayList<>();
//
//                matchingResultsListByCorpName.forEach(itemNew -> {
//                    String newPolicyName = itemNew.getPolicyName();
//                    for (int i = 0; i < listMatchResult.size(); i++) {
//                        MatchingResults itemOld = listMatchResult.get(i);
//                        String oldPolicyName = itemOld.getPolicyName();
//                        if (Objects.equals(oldPolicyName, newPolicyName)) {
//                            oldIndex.add(i);
//                        }
//                    }
//                });
//                if (oldIndex.size() > 0) {
//                    oldIndex.forEach(listMatchResult::remove);
//                }
//                listMatchResult.addAll(matchingResultsListByCorpName);
//            }
//            //插入代码-如上
//
//            Map<String, Object> map = new HashMap<>();
//            map.put("total", total);
//            map.put("listMatchResult", listMatchResult);
//
//
//            serverResponse = ServerResponse.createSuccess("查询成功", map);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//
//        return serverResponse;
//    }

    @Override
    public ServerResponse<?> searchMatchingResult(Integer pageNum, Integer pageSize, String policiesName, String corpName) {
        ServerResponse<?> serverResponse = ServerResponse.createError("查询失败");
        try {

            List<MatchingResults> listMatchResult = new ArrayList<>();
            List<String> ids = new ArrayList<>();
            if (policiesName != null && !"".equals(policiesName)) {
                TpoliciesApi tpoliciesApi = new TpoliciesApi();
                TPoliciesDTO tPoliciesDTO1 = new TPoliciesDTO();
                tPoliciesDTO1.set$LikeQueryField("name");
                tPoliciesDTO1.setName(policiesName);
                //tPoliciesDTO1.setatsandboxDBId(ConstantExt._SAND_BOX_ID);
                List<TPoliciesDTOResponse> listPolicies = tpoliciesApi.findtPoliciesUsingPOST(tPoliciesDTO1).getData();
                if (listPolicies != null && listPolicies.size() > 0) {
                    ids = listPolicies.stream().map(p -> {
                        return p.getId();
                    }).collect(Collectors.toList());
                }
            }

            TmatchingresultsApi tmatchingresultsApi = new TmatchingresultsApi();
            TMatchingResultsDTO query = new TMatchingResultsDTO();
            //query.setatsandboxDBId(ConstantExt._SAND_BOX_ID);
            query.setUserInfo(corpName);
            if (ids != null && ids.size() > 0) {
                query.set$MultiValueField("policy");
                query.setPolicy(listToString(ids));
            }

            List<TMatchingResultsDTOResponse> listMatchingResult = tmatchingresultsApi.findtMatchingResultsUsingPOST(query).getData();
            if (listMatchingResult != null && listMatchingResult.size() > 0) {
                for (TMatchingResultsDTOResponse tMatchingResultsDTO1 : listMatchingResult) {
                    String policyName = (String) tMatchingResultsDTO1.getPolicy();
                    String policystring = tMatchingResultsDTO1.getPolicystring();
                    String url = tMatchingResultsDTO1.getUrl();
                    String applicationCondition = tMatchingResultsDTO1.getApplicationCondition();
                    String competmentDepartment = tMatchingResultsDTO1.getCompetentDepartment();
                    if (competmentDepartment != null && !"".equals(competmentDepartment)) {
                        try{
                            Object parse = JSONObject.parse(competmentDepartment);
                            JSONObject parseObject = JSONObject.parseObject(parse.toString());
                            competmentDepartment = parseObject.getString("name");
                        }catch (Exception e){
                            competmentDepartment = tMatchingResultsDTO1.getCompetentDepartment();
                        }

                    }
                    String startdate = tMatchingResultsDTO1.getStartdate();
                    if (startdate != null && !"".equals(startdate)) {
                        startdate = startdate.split(" ")[0];
                    }
                    String enddate = tMatchingResultsDTO1.getEnddate();
                    if (enddate != null && !"".equals(enddate)) {
                        enddate = enddate.split(" ")[0];
                    }
                    String attachment = null;
                    String filePath = "";
                    String fileName = "";
                    List<Object> listAttachment = tMatchingResultsDTO1.getAttachment();
                    if (listAttachment != null && listAttachment.size() > 0) {
                        attachment = (String) listAttachment.get(0);
                        JSONObject parseObject = JSONObject.parseObject(attachment);
                        filePath = parseObject.getString("filePath");
                        fileName = parseObject.getString("fileName");
                        if (fileName != null && !"".equals(fileName)) {
                            if (fileName.substring(0).equals("“")) {
                                fileName = fileName.replaceAll("“", "");
                            }
                        }
                    }
                    BigDecimal matchingDegree = tMatchingResultsDTO1.getMatchingDegree();
                    String remark = tMatchingResultsDTO1.getNote();
                    MatchingResults matchingResults = new MatchingResults();
                    matchingResults.setPolicyName(policystring);
                    matchingResults.setDeclarationConditions(applicationCondition);
                    matchingResults.setCompetentDepartment(competmentDepartment);
                    matchingResults.setStartDate(startdate);
                    matchingResults.setRemark(remark);
                    matchingResults.setDeclarationLink(url);
                    matchingResults.setEndDate(enddate);
                    matchingResults.setAttachmentName(fileName);
                    matchingResults.setAttachmentUrl(filePath);
                    matchingResults.setScore(matchingDegree.intValue());
                    matchingResults.setUserInfo(tMatchingResultsDTO1.getUserInfo());
                    listMatchResult.add(matchingResults);
                }
            }
            //插入代码-如下
            List<MatchingResults> matchingResultsListByCorpName = matchingResultsListByCorpName(corpName);

            int sIndex = (pageNum - 1) * pageSize;
            if (matchingResultsListByCorpName.size() > 0 && listMatchResult.size() > 0) {
                Iterator<MatchingResults> iterator = listMatchResult.iterator();
                while (iterator.hasNext()) {
                    MatchingResults next = iterator.next();
                    String policyNameOld = next.getPolicyName();
                    matchingResultsListByCorpName.forEach(item -> {
                        String policyNameNew = item.getPolicyName();
                        if (Objects.equals(policyNameOld, policyNameNew)) {
                            iterator.remove();
                        }
                    });
                }
                listMatchResult.addAll(matchingResultsListByCorpName);
            } else if (matchingResultsListByCorpName.size() > 0) {
                listMatchResult.addAll(matchingResultsListByCorpName);
            }

            List<MatchingResults> result = listMatchResult.stream().skip(sIndex).limit(pageSize).collect(Collectors.toList());
            //插入代码-如上
            //排序
            try {
                PolicyCondCal.sortEntity(result);
            }catch (Exception e){
                log.info("排序数据异常：【{}】",e);
            }
            Map<String, Object> map = new HashMap<>();
            map.put("total", listMatchResult.size());
            map.put("listMatchResult", result);
            serverResponse = ServerResponse.createSuccess("查询成功", map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return serverResponse;
    }

    @Override
    public ServerResponse<?> searchMatchingResult(Integer pageNum, Integer pageSize, String corpName) {
        ServerResponse<?> serverResponse = ServerResponse.createError("查询失败");
        try {

            List<MatchingResults> listMatchResult = new ArrayList<>();

            TmatchingresultsApi tmatchingresultsApi = new TmatchingresultsApi();
            TMatchingResultsDTO query = new TMatchingResultsDTO();
            query.setUserInfo(corpName);

            List<TMatchingResultsDTOResponse> listMatchingResult = tmatchingresultsApi.findtMatchingResultsUsingPOST(query).getData();
            if (listMatchingResult != null && listMatchingResult.size() > 0) {
                for (TMatchingResultsDTOResponse tMatchingResultsDTO1 : listMatchingResult) {
                    String policyName = (String) tMatchingResultsDTO1.getPolicy();
                    String policystring = tMatchingResultsDTO1.getPolicystring();
                    String url = tMatchingResultsDTO1.getUrl();
                    String applicationCondition = tMatchingResultsDTO1.getApplicationCondition();
                    String competmentDepartment = tMatchingResultsDTO1.getCompetentDepartment();
                    if (competmentDepartment != null && !"".equals(competmentDepartment)) {
                        try{
                            Object parse = JSONObject.parse(competmentDepartment);
                            JSONObject parseObject = JSONObject.parseObject(parse.toString());
                            competmentDepartment = parseObject.getString("name");
                        }catch (Exception e){
                            competmentDepartment = tMatchingResultsDTO1.getCompetentDepartment();
                        }

                    }
                    String startdate = tMatchingResultsDTO1.getStartdate();
                    if (startdate != null && !"".equals(startdate)) {
                        startdate = startdate.split(" ")[0];
                    }
                    String enddate = tMatchingResultsDTO1.getEnddate();
                    if (enddate != null && !"".equals(enddate)) {
                        enddate = enddate.split(" ")[0];
                    }
                    String attachment = null;
                    String filePath = "";
                    String fileName = "";
                    List<Object> listAttachment = tMatchingResultsDTO1.getAttachment();
                    if (listAttachment != null && listAttachment.size() > 0) {
                        attachment = (String) listAttachment.get(0);
                        JSONObject parseObject = JSONObject.parseObject(attachment);
                        filePath = parseObject.getString("filePath");
                        fileName = parseObject.getString("fileName");
                        if (fileName != null && !"".equals(fileName)) {
                            if (fileName.substring(0).equals("“")) {
                                fileName = fileName.replaceAll("“", "");
                            }
                        }

                    }
                    BigDecimal matchingDegree = tMatchingResultsDTO1.getMatchingDegree();
                    String remark = tMatchingResultsDTO1.getNote();
                    MatchingResults matchingResults = new MatchingResults();
                    matchingResults.setPolicyName(policystring);
                    matchingResults.setDeclarationConditions(applicationCondition);
                    matchingResults.setCompetentDepartment(competmentDepartment);
                    matchingResults.setStartDate(startdate);
                    matchingResults.setRemark(remark);
                    matchingResults.setDeclarationLink(url);
                    matchingResults.setEndDate(enddate);
                    matchingResults.setAttachmentName(fileName);
                    matchingResults.setAttachmentUrl(filePath);
                    matchingResults.setScore(matchingDegree.intValue());
                    matchingResults.setUserInfo(tMatchingResultsDTO1.getUserInfo());
                    listMatchResult.add(matchingResults);
                }
            }
            //排序
            try {
                PolicyCondCal.sortEntity(listMatchResult);
            }catch (Exception e){
                log.info("排序数据异常：【{}】",e);
            }
            Map<String, Object> map = new HashMap<>();
            map.put("total", listMatchResult.size());
            map.put("listMatchResult", listMatchResult);
            serverResponse = ServerResponse.createSuccess("查询成功", map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return serverResponse;
    }

    private List<MatchingResults> matchingResultsListByCorpName(String corpName) {
        List<TenterprisesDTOResponse> enterprisesListByName = enterprisesListByName(corpName);

        List<MatchingResults> matchingResultsAll = new ArrayList<>();

        if (enterprisesListByName != null && enterprisesListByName.size() > 0) {
            enterprisesListByName.forEach(enterprises -> {
                String category = enterprises.getCategory();
                if (StringUtils.isNotEmpty(category)) {
                    JSONArray jsonArray = JSON.parseObject(category, JSONArray.class);
                    if (jsonArray != null && jsonArray.size() > 0) {
                        jsonArray.forEach(jsonElement -> {
                            String s = JSON.toJSONString(jsonElement);
                            JSONObject jsonObject = JSON.parseObject(s);
                            String name = jsonObject.getString("name");
                            List<TPoliciesDTOResponse> policiesListByName = policiesListByName(name);
                            if (policiesListByName != null) {
                                List<MatchingResults> matchingResultsList = policiesListByName.stream().map(item -> {
                                    String policyName = item.getName();
                                    String applicationCondition = item.getCondition();
                                    String competmentDepartment = item.getCompetentDepartment();
                                    JSONObject competmentDepartmentJson = JsonUtils.jsonStrToJson(competmentDepartment);
                                    if (competmentDepartmentJson != null) {
                                        competmentDepartment = competmentDepartmentJson.getString("name");
                                    }
                                    String startDate = item.getStartDate();
                                    String endDate = item.getEndDate();
                                    String fileName = "";
                                    String filePath = "";
                                    List<Object> attachment = item.getAttachment();
                                    if (attachment != null && attachment.size() > 0) {
                                        Object o = attachment.get(0);
                                        JSONObject oJson = JsonUtils.objToJson(o);
                                        if (oJson != null) {
                                            fileName = oJson.getString("fileName");
                                            filePath = oJson.getString("filePath");
                                        }

                                    }
                                    MatchingResults matchingResults = new MatchingResults();
                                    matchingResults.setPolicyName(policyName);
                                    matchingResults.setDeclarationConditions(applicationCondition);
                                    matchingResults.setCompetentDepartment(competmentDepartment);
                                    matchingResults.setStartDate(startDate);
                                    matchingResults.setEndDate(endDate);
                                    matchingResults.setAttachmentName(fileName);
                                    matchingResults.setAttachmentUrl(filePath);
                                    matchingResults.setScore(100);
                                    return matchingResults;
                                }).collect(Collectors.toList());
                                matchingResultsAll.addAll(matchingResultsList);
                            }
                        });
                    }
                }
            });
        }
        return matchingResultsAll;
    }

    private List<TPoliciesDTOResponse> policiesListByName(String name) {
        TPoliciesDTO query = new TPoliciesDTO();
        query.setName(name);
        //query.setatsandboxDBId(ConstantExt._SAND_BOX_ID);
        List<TPoliciesDTOResponse> data = tpoliciesApi.findtPoliciesUsingPOST(query).getData();
        if (data != null && data.size() > 0) {
            return data;
        }
        return null;
    }

    private List<TenterprisesDTOResponse> enterprisesListByName(String name) {
        TenterprisesDTO query = new TenterprisesDTO();
        query.setName(name);
        //query.setatsandboxDBId(ConstantExt._SAND_BOX_ID);
        List<TenterprisesDTOResponse> data = tenterprisesApi.findtEnterprisesUsingPOST(query).getData();
        if (data != null && data.size() > 0) {
            return data;
        }
        return null;
    }

    public static String listToString(List<String> ids) {
        String id = ids.toString().replaceAll("\\[", "").replaceAll("\\]", "").replaceAll(" ", "");
        return id;
    }

    @Override
    public ServerResponse<?> insertPolicy(PolicyEntity policy) {
        try {
            // 企业名称
            String enterpriseName = policy.getEnterpriseName();
            // 企业所属区域
            String enterpriseArea = policy.getEnterpriseArea();
            // 注册资本
            Integer registeredCapital = policy.getRegisteredCapital();
            // 注册时间
            String registeredTime = policy.getRegisteredTime();
            // 所属行业
            List<String> industrys = policy.getIndustrys();
            // 主要产品或服务
            String mainProductsOrServices = policy.getMainProductsOrServices();
            // 所属园区
            String park = policy.getPark();
            // 企业规模
            String enterpriseScale = policy.getEnterpriseScale();
            // 独立法人
            String independentLegalPerson = policy.getIndependentLegalPerson();
            // 是否违法
            String dishonesty = policy.getDishonesty();
            // 参与标准制定
            Integer participateDevelopment = policy.getParticipateDevelopment();
            // 专业化 是否在行业细分市场领域内国内排名前10
            String industryTop10 = policy.getIndustryTop10();
            // 市占率
            String marketShare = policy.getMarketShare();
            // 特：品牌具有一定特色，获得过驰名商标、著名商标、名牌产品等荣誉称号（项）
            Integer brandCharacteristics = policy.getBrandCharacteristics();
            // 新：提供产品或服务满足“四新”经济发展特征，具有一定创新性，估值 （亿美元）1
            String productOrService = policy.getProductOrService();
            // 新：提供产品或服务满足“四新”经济发展特征，具有一定创新性，估值 （亿美元）2 数字
            BigDecimal productOrService2 = policy.getProductOrService2();
            // 企业资质
            List<String> enterpriseQualification = policy.getEnterpriseQualification();
            String enterpriseQualificationStr = "";
            if (enterpriseQualification != null && enterpriseQualification.size() > 0) {
                enterpriseQualificationStr = enterpriseQualificationStr.replaceAll("\\[", "").replaceAll("\\]", "");
            }
            // 职工总数
            Integer empTotal = policy.getEmpTotal();
            // 研发人员数
            Integer rOrDpersonnel = policy.getDpersonnel();
            // 大前年研发费用
            Integer rOrDexpensesInTheYearBefore = policy.getDexpensesInTheYearBefore();
            // 前年研发费用
            Integer rOrDExpensesOfThePreviousYear = policy.getDexpensesOfThePreviousYear();
            // 去年研发费用
            Integer rOrDExpensesLastYear = policy.getDexpensesLastYear();
            // 大前年营业收入
            Integer yearBeforeTheUniversity = policy.getYearBeforeTheUniversity();
            // 前年营业收入
            Integer businessIncomeOfThePpreviousYear = policy.getBusinessIncomeOfThePpreviousYear();
            // 去年度营业收入
            Integer businessIncomeOfLastYear = policy.getBusinessIncomeOfLastYear();
            // 发明专利数
            Integer inventionPatentsNumberOneClass = policy.getInventionPatentsNumberOneClass();
            // 集成电路数
            Integer integratedCircuitsOneClass = policy.getIntegratedCircuitsOneClass();
            // 实用新型专利数
            Integer utilityModelPatentsTwoClass = policy.getUtilityModelPatentsTwoClass();
            // 外观专利数
            Integer appearancePatentsTwoClass = policy.getAppearancePatentsTwoClass();
            // 软件著作权数
            Integer softwareCopyrightTwoClass = policy.getSoftwareCopyrightTwoClass();
            // 上年度高新产品
            Integer highTechProductsOfLastYear = policy.getHighTechProductsOfLastYear();
            // 科技成果转化
            Integer technologicalAchievements = policy.getTechnologicalAchievements();
            // 研发组织管理 是否建立制定并完善《企业研发的组织管理制度》等研发管理制度体系（知识产权保护、人才引进培养、创新激励）
            String formulateAndImproved = policy.getFormulatedAndImproved();
            // 产学研 是否同1所以上大学或科研院校签订产学研合作协议。
            String researchInstitution = policy.getResearchInstitution();
            // 设备研发
            String researchAndDevelopmentSite = policy.getResearchAndDevelopmentSite();
            // 是否有良好的经营管理团队，有较强的风险控制机制和健全的规章制度
            String rulesAndRegulations = policy.getRulesAndRegulations();
            // 是否有在建项目
            String projectsUnderConstruction = policy.getProjectsUnderConstruction();
            // 项目内容
            String projectContent = policy.getProjectContent();
            // 年服务中小企业
            Integer annualNumberOfSMEs = policy.getAnnualNumberOfSMEs();
            // 资产总额
            Integer totalAssets = policy.getTotalAssets();
            // 净资产（万元）
            Integer netAssets = policy.getNetAssets();
            // 净资产增长率
            Integer growthRateOfNetAssets = policy.getGrowthRateOfNetAssets();
            // 负债总额（万元）
            Integer totalLiabilities = policy.getTotalLiabilities();
            // 大前年净利润（万元）
            Integer annualNetProfitOfThePreviousYear = policy.getAnnualNetProfitOfThePreviousYear();
            // 前年净利润（万元）
            Integer netProfitOfThePreviousYear = policy.getNetProfitOfThePreviousYear();
            // 去年度净利润（万元）
            Integer netProfitOfLastYear = policy.getNetProfitOfLastYear();
            // 上一年度税收总额（万元）
            Integer totalTaxRevenueOfLastYear = policy.getTotalTaxRevenueOfLastYear();
            // 去年节约能耗(KWh）
            Integer energySavingLastYear = policy.getEnergySavingLastYear();
            // 是否留学人员
            String overseasStudentsOrNot = policy.getOverseasStudentsOrNot();
            // 年龄
            Integer age = policy.getAge();
            // 户籍
            String householdRegister = policy.getHouseholdRegister();
            // 主持或参与项目/课题情况
            String hostingOrParticipatingInProjects = policy.getHostingOrParticipatingInProjects();
            // 用户信息
            String userInfo = policy.getCorpName();


            TaccuratematchingApi taccuratematchingApi = new TaccuratematchingApi();
            TAccurateMatchingDTOQuery tAccurateMatchingQuery = new TAccurateMatchingDTOQuery();
//    		tAccurateMatchingQuery.setUserInfo(userInfo);
            TAccurateMatchingDTOUpdate tAccurateMatchingUpdate = new TAccurateMatchingDTOUpdate();
            tAccurateMatchingUpdate.setName(enterpriseName);
            tAccurateMatchingUpdate.setArea(enterpriseArea);
            tAccurateMatchingUpdate.setRegisteredCapital(new BigDecimal(registeredCapital));
            tAccurateMatchingUpdate.setSigndate(registeredTime);
//    		tAccurateMatchingUpdate.setIndustry(industrys);
            tAccurateMatchingUpdate.setProductorservice(mainProductsOrServices);
            tAccurateMatchingUpdate.setPark(park);
            tAccurateMatchingUpdate.setScale(enterpriseScale);
            tAccurateMatchingUpdate.setIndividual(independentLegalPerson);
            tAccurateMatchingUpdate.setWhetherviolate(dishonesty);
            tAccurateMatchingUpdate.setStandardSettingAmount(participateDevelopment);
            tAccurateMatchingUpdate.setMarketRanking(industryTop10);
            tAccurateMatchingUpdate.setMarketoccupancy(marketShare);
            tAccurateMatchingUpdate.setHonor(brandCharacteristics);
            tAccurateMatchingUpdate.setDescribe(productOrService);
            tAccurateMatchingUpdate.setEstimatevalue(productOrService2);
            tAccurateMatchingUpdate.setQuality(enterpriseQualificationStr);
            tAccurateMatchingUpdate.setWorkernumber(empTotal);
            tAccurateMatchingUpdate.setRdnumber(rOrDpersonnel);
            tAccurateMatchingUpdate.setRdExpensesSpentThreeYearsAgo(new BigDecimal(rOrDexpensesInTheYearBefore));
            tAccurateMatchingUpdate.setRdExpensesSpentTwoYearsAgo(new BigDecimal(rOrDExpensesOfThePreviousYear));
            tAccurateMatchingUpdate.setRdExpensesSpentLastYear(new BigDecimal(rOrDExpensesLastYear));
            tAccurateMatchingUpdate.setTyaincome(yearBeforeTheUniversity);
            tAccurateMatchingUpdate.setYblastyearincome(businessIncomeOfThePpreviousYear);
            tAccurateMatchingUpdate.setLastyearincome(businessIncomeOfLastYear);
            tAccurateMatchingUpdate.setInvent(inventionPatentsNumberOneClass);
            tAccurateMatchingUpdate.setElectric(integratedCircuitsOneClass);
            tAccurateMatchingUpdate.setPracticalnew(utilityModelPatentsTwoClass);
            tAccurateMatchingUpdate.setAppearance(appearancePatentsTwoClass);
            tAccurateMatchingUpdate.setSoftware(softwareCopyrightTwoClass);
            tAccurateMatchingUpdate.setHightechincome(highTechProductsOfLastYear);
            tAccurateMatchingUpdate.setTechtransfer(technologicalAchievements);
            tAccurateMatchingUpdate.setWanshantixi(formulateAndImproved);
            tAccurateMatchingUpdate.setXueyanhezuo(researchInstitution);
            tAccurateMatchingUpdate.setChangdishebei(researchAndDevelopmentSite);
            tAccurateMatchingUpdate.setTuanduifengkong(rulesAndRegulations);
            tAccurateMatchingUpdate.setUnderconstruction(projectsUnderConstruction);
            tAccurateMatchingUpdate.setContent(projectContent);
            tAccurateMatchingUpdate.setServe(annualNumberOfSMEs);
            tAccurateMatchingUpdate.setAsset(totalAssets);
            tAccurateMatchingUpdate.setNetasset(netAssets);
            tAccurateMatchingUpdate.setNetassetrise(new BigDecimal(growthRateOfNetAssets));
            tAccurateMatchingUpdate.setLiability(totalLiabilities);
            tAccurateMatchingUpdate.setTyaprofit(annualNetProfitOfThePreviousYear);
            tAccurateMatchingUpdate.setYblyprofit(netProfitOfThePreviousYear);
            tAccurateMatchingUpdate.setLyprofit(netProfitOfLastYear);
            tAccurateMatchingUpdate.setLytax(totalTaxRevenueOfLastYear);
            tAccurateMatchingUpdate.setLysaveenergy(energySavingLastYear);
            tAccurateMatchingUpdate.setGoabroad(String.valueOf(overseasStudentsOrNot));
            tAccurateMatchingUpdate.setAge(age);
            tAccurateMatchingUpdate.setCensus(householdRegister);
            tAccurateMatchingUpdate.setProjects(hostingOrParticipatingInProjects);
            tAccurateMatchingUpdate.setUserInfo(userInfo);

            SaveOrUpdatetAccurateMatchingDTO saveOrUpdatetAccurateMatchingDTO1 = new SaveOrUpdatetAccurateMatchingDTO();
            //tAccurateMatchingUpdate.setatsandboxDBId(ConstantExt._SAND_BOX_ID);
            saveOrUpdatetAccurateMatchingDTO1.setQuery(tAccurateMatchingQuery);
            saveOrUpdatetAccurateMatchingDTO1.setUpdate(tAccurateMatchingUpdate);
            String message = taccuratematchingApi.saveOrUpdatetAccurateMatchingUsingPOST(saveOrUpdatetAccurateMatchingDTO1).getMessage();
            System.out.println("精确匹配入库: " + message);


//    		TAccurateMatchi


        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public ServerResponse<?> fastMatching(String token) {
        ServerResponse<?> serverResponse = ServerResponse.createError("匹配失败");
        try {
            String corpName = TokenCommon.getCorpNameByToken(token);
            if (corpName != null && !"".equals(corpName)) {
                TmatchingresultsApi tmatchingresultsApi2 = new TmatchingresultsApi();
                TMatchingResultsDTO tMatchingResultsQuery2 = new TMatchingResultsDTO();
                //tMatchingResultsQuery2.setatsandboxDBId(ConstantExt._SAND_BOX_ID);
                tMatchingResultsQuery2.setUserInfo(corpName);
                List<TMatchingResultsDTODelete> dataDel = new ArrayList<>();
                List<TMatchingResultsDTOResponse> data = tmatchingresultsApi2.findtMatchingResultsUsingPOST(tMatchingResultsQuery2).getData();
                if (data != null && data.size() > 0) {
                    for (TMatchingResultsDTOResponse tMatchingResultsDTO1 : data) {
                        TMatchingResultsDTODelete tMatchingResultsDTO1Del = new TMatchingResultsDTODelete();
                        tMatchingResultsDTO1Del.setId(tMatchingResultsDTO1.getId());
                        //tMatchingResultsDTO1Del.setatsandboxDBId(ConstantExt._SAND_BOX_ID);
                        dataDel.add(tMatchingResultsDTO1Del);
                    }
                    String message = tmatchingresultsApi2.deletetMatchingResultsUsingPOST(dataDel).getMessage();
                    System.out.println("公司名称: " + corpName + " 删除:" + message);
                }

                // TODO 快速匹配
                RestTemplate restTemplate = new RestTemplate();
                HttpHeaders httpHeaders = new HttpHeaders();
                httpHeaders.add("Content-Type", "application/json");
                HttpEntity<String> httpEntity = new HttpEntity<>(null, httpHeaders);
                String url1 = "https://php.79cloud.cn/api/Agent/userTokenGet?agent_token=493a616fcca354ef24db997c105b5cca";
                ResponseEntity<String> response = restTemplate.exchange(url1, HttpMethod.POST, httpEntity, String.class);
                Object parse = JSONObject.parse(response.getBody());
                JSONObject dataStr = JSONObject.parseObject(parse.toString());
                Integer code1 = dataStr.getInteger("data");
                if (code1 != 0) {
                    String userToken = dataStr.getString("msg");
                    RestTemplate restTemplate2 = new RestTemplate();
                    HttpHeaders httpHeaders2 = new HttpHeaders();
                    httpHeaders2.add("Content-Type", "application/json");
                    HttpEntity<String> httpEntity2 = new HttpEntity<>(null, httpHeaders2);
                    String url2 = "https://php.79cloud.cn/api/Agent/getBasicData?agent_token=493a616fcca354ef24db997c105b5cca&user_token=" + userToken + "&name=" + corpName;
                    ResponseEntity<String> responseEntity = restTemplate2.exchange(url2, HttpMethod.POST, httpEntity2, String.class);
                    Object parse2 = JSONObject.parse(responseEntity.getBody());
                    JSONObject dataStr2 = JSONObject.parseObject(parse2.toString());
                    Integer code2 = dataStr2.getInteger("data");
                    if (code2 != 0) {
                        Object msg = dataStr2.get("msg");
                        JSONObject parseObjectMsg = JSONObject.parseObject(msg.toString());
                        Object basic = parseObjectMsg.get("basic");
                        JSONObject parseObjectBasic = JSONObject.parseObject(basic.toString());
                        String name = parseObjectBasic.getString("name");
                        String town = parseObjectBasic.getString("town");
                        String reg_date = parseObjectBasic.getString("reg_date");
                        String scale = parseObjectBasic.getString("scale");
                        String is_ind = parseObjectBasic.getString("is_ind");
                        String is_hightech = parseObjectBasic.getString("is_hightech");
                        String is_zjtx = parseObjectBasic.getString("is_zjtx");
                        String is_tech = parseObjectBasic.getString("is_tech");


                        Object invent = parseObjectMsg.get("invent");
                        JSONObject parseObjectInvent = JSONObject.parseObject(invent.toString());
                        String employee = parseObjectInvent.getString("employee");
                        String num_ip = parseObjectInvent.getString("num_ip");
                        String num_ntype = parseObjectInvent.getString("num_ntype");
                        String num_out = parseObjectInvent.getString("num_out");
                        String num_copyright = parseObjectInvent.getString("num_copyright");
                        String num_ic = parseObjectInvent.getString("num_ic");

                        Object run = parseObjectMsg.get("run");
                        JSONObject parseObjectRun = JSONObject.parseObject(run.toString());
                        String assets = parseObjectRun.getString("assets");
                        String debt = parseObjectRun.getString("debt");
                        String rate_ad = parseObjectRun.getString("rate_ad");
                        String income2 = parseObjectRun.getString("income2");
                        String income1 = parseObjectRun.getString("income1");
                        String income = parseObjectRun.getString("income");
                        String rate_income = parseObjectRun.getString("rate_income");
                        String rate3_income = parseObjectRun.getString("rate3_income");
                        String net_profit2 = parseObjectRun.getString("net_profit2");
                        String net_profit1 = parseObjectRun.getString("net_profit1");
                        String net_profit = parseObjectRun.getString("net_profit");
                        String rate_net_profit = parseObjectRun.getString("rate_net_profit");
                        String rate3_net_profit = parseObjectRun.getString("rate3_net_profit");
                        String tax = parseObjectRun.getString("tax");

                        // TODO 政策匹配
                        TmatchingresultsApi tmatchingresultsApi = new TmatchingresultsApi();

                        // 上海市高新技术企业认定 得分
                        StringBuffer sb1 = new StringBuffer();
                        // 注册时间
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
                        Date startDate = new Date();
                        String currTime = sdf.format(startDate);
                        // 成立时间是否大于1年
                        boolean establishmentTime = false;
                        if (reg_date != null && !"".equals(reg_date)) {
                            establishmentTime = DateUtils.dayCompare(reg_date, currTime, 365);
                        }
                        if (!establishmentTime) {
                            sb1.append("成立年限不足1年，建议明年提交申请，并做好知识产权储备、研发辅助账、高新专项审计、产学研合作、研发组织管理等前期准备。\n");
                        }
                        // 高新
                        boolean gaoxin = false;
                        if (is_hightech != null && "1".equals(is_hightech)) {
                            gaoxin = true;
                        }
                        // 是否违法
                        boolean isweifa = true;

                        // 科技人员占比
                        boolean kejiemp = true;

                        // 前端 近3年研发费用占比
                        boolean incomequnianb = true;
//
                        // 上年度高新服务收入占比
                        boolean shangniandugaoxinfuwu = true;

                        TpoliciesApi tpoliciesApi = new TpoliciesApi();

                        DecimalFormat df = new DecimalFormat("0.00");


                        // TODO
                        if (establishmentTime && gaoxin && isweifa && kejiemp && incomequnianb) {
//				    		if(true) {
                            // 匹配政策
                            TPoliciesDTO tPoliciesQuery = new TPoliciesDTO();
                            tPoliciesQuery.setName("上海市高新技术企业认定");
                            //tPoliciesQuery.setatsandboxDBId(ConstantExt._SAND_BOX_ID);
                            List<TPoliciesDTOResponse> listPolicies = tpoliciesApi.findtPoliciesUsingPOST(tPoliciesQuery).getData();
                            if (listPolicies != null && listPolicies.size() > 0) {
                                TPoliciesDTOResponse tPoliciesDTO1 = listPolicies.get(0);
                                // 政策ID
                                String policiesId = tPoliciesDTO1.getId();
                                // 政策名称
                                String policiesName = tPoliciesDTO1.getName();
                                // 申报条件
                                String condition = tPoliciesDTO1.getCondition();
                                // 申报入口
                                String url = tPoliciesDTO1.getEntrance();
                                // 主管部门
                                String competmentDepartment = tPoliciesDTO1.getCompetentDepartment();
                                // 申报日期
                                String startDateResult = tPoliciesDTO1.getStartDate();
                                if (startDateResult != null && !"".equals(startDateResult)) {
                                    startDateResult = startDateResult.split(" ")[0];
                                }
                                String endDateResult = tPoliciesDTO1.getEndDate();
                                if (endDateResult != null && !"".equals(endDateResult)) {
                                    endDateResult = endDateResult.split(" ")[0];
                                }
                                // 附件
                                List<Object> listAttachment = tPoliciesDTO1.getAttachment();


                                Integer fen = 0;

                                // 知识产权
                                Integer yiClass = 0;
                                if (num_ip != null && num_ic != null) {
                                    yiClass = Integer.valueOf(num_ip) + Integer.valueOf(num_ic);
                                }
                                if (num_ntype != null && num_out != null && num_copyright != null) {
                                    Integer twoClass = Integer.valueOf(num_ntype) + Integer.valueOf(num_out) + Integer.valueOf(num_copyright);
                                    if (yiClass >= 1 && twoClass > 6) {
                                        fen += 27;
                                    } else if (twoClass >= 6) {
                                        fen += 24;
                                    } else if (twoClass >= 4) {
                                        fen += 18;
                                    } else if (twoClass >= 3) {
                                        fen += 12;
                                    } else if (twoClass >= 2) {
                                        fen += 6;
                                    } else if (twoClass < 2) {
                                        fen += 0;
                                    }
                                    if (twoClass <= 4) {
                                        sb1.append("知识产权数量偏少，请加强知识产权储备，建议申请软件著作权或实用新型专利，加快储备时间。\n");
                                    }
                                }

//					    		rate_net_profit = "0.24";
                                Number m1 = null;
                                if (rate_net_profit != null && !"".equals(rate_net_profit)) {
                                    Double d1 = Double.parseDouble(rate_net_profit);
                                    String s1 = df.format(d1);
                                    // 净资产增长率
                                    m1 = df.parse(s1);

                                    Double doubleM1 = m1.doubleValue() * 100;
                                    int intValueM1 = doubleM1.intValue();

                                    if (intValueM1 >= 35) {
                                        fen += 10;
                                    } else if (intValueM1 >= 25) {
                                        fen += 8;
                                    } else if (intValueM1 >= 15) {
                                        fen += 6;
                                    } else if (intValueM1 >= 5) {
                                        fen += 4;
                                    } else if (intValueM1 >= 0) {
                                        fen += 2;
                                    } else if (intValueM1 < 0) {
                                        fen += 0;
                                    }
                                }

//					    		rate_income = "0.74";
                                // 收入增长率
                                Number m2 = null;
                                if (rate_income != null && !"".equals(rate_income)) {
                                    Double d2 = Double.parseDouble(rate_income);
                                    String s2 = df.format(d2);
                                    m2 = df.parse(s2);
                                    Double doubleM1 = m2.doubleValue() * 100;
                                    int intValueM1 = doubleM1.intValue();
                                    if (intValueM1 >= 35) {
                                        fen += 10;
                                    } else if (intValueM1 >= 25) {
                                        fen += 8;
                                    } else if (intValueM1 >= 15) {
                                        fen += 6;
                                    } else if (intValueM1 >= 5) {
                                        fen += 4;
                                    } else if (intValueM1 >= 0) {
                                        fen += 2;
                                    } else if (intValueM1 < 0) {
                                        fen += 0;
                                    }
                                }

                                if (sb1.length() == 0 && fen >= 90) {
                                    sb1.append("建议申报");
                                }

                                TMatchingResultsDTOQuery tMatchingResultsQuery = new TMatchingResultsDTOQuery();
                                TMatchingResultsDTOUpdate tMatchingResultsUpdate = new TMatchingResultsDTOUpdate();
                                tMatchingResultsUpdate.setName(policiesId);
                                tMatchingResultsUpdate.setPolicystring(policiesName);
                                tMatchingResultsUpdate.setApplicationCondition(condition);
                                tMatchingResultsUpdate.setCompetentDepartment(competmentDepartment);
                                tMatchingResultsUpdate.setStartdate(startDateResult);
                                tMatchingResultsUpdate.setEnddate(endDateResult);
                                tMatchingResultsUpdate.setNote(sb1.toString());
                                tMatchingResultsUpdate.setUrl(url);
                                tMatchingResultsUpdate.setApplicationDate(startDateResult + "-" + endDateResult);
                                tMatchingResultsUpdate.setAttachment(listAttachment);
                                tMatchingResultsUpdate.setMatchingDegree(new BigDecimal(fen));
                                tMatchingResultsUpdate.setUserInfo(corpName);

                                SaveOrUpdatetMatchingResultsDTO saveOrUpdatetMatchingResultsDTO1 = new SaveOrUpdatetMatchingResultsDTO();
                                //tMatchingResultsUpdate.setatsandboxDBId(ConstantExt._SAND_BOX_ID);
                                saveOrUpdatetMatchingResultsDTO1.setQuery(tMatchingResultsQuery);
                                saveOrUpdatetMatchingResultsDTO1.setUpdate(tMatchingResultsUpdate);
                                String message = tmatchingresultsApi.saveOrUpdatetMatchingResultsUsingPOST(saveOrUpdatetMatchingResultsDTO1).getMessage();
                                System.out.println("上海市高新技术企业认定匹配结果: " + message);
                            }

                        } else {
                            System.out.println("快速匹配: 上海市高新技术企业认定 不满足必要条件");
                        }


                        // TODO 上海市高新技术企业入库培育
                        if (establishmentTime && gaoxin && isweifa && kejiemp && incomequnianb) {

                            // 匹配政策
                            TPoliciesDTO tPoliciesQuery = new TPoliciesDTO();
                            tPoliciesQuery.setName("上海市高新技术企业入库培育");
                            //tPoliciesQuery.setatsandboxDBId(ConstantExt._SAND_BOX_ID);
                            List<TPoliciesDTOResponse> listPolicies = tpoliciesApi.findtPoliciesUsingPOST(tPoliciesQuery).getData();
                            if (listPolicies != null && listPolicies.size() > 0) {
                                TPoliciesDTOResponse tPoliciesDTO1 = listPolicies.get(0);
                                // 政策ID
                                String policiesId = tPoliciesDTO1.getId();
                                // 政策名称
                                String policiesName = tPoliciesDTO1.getName();
                                // 申报条件
                                String condition = tPoliciesDTO1.getCondition();
                                // 申报入口
                                String url = tPoliciesDTO1.getEntrance();
                                // 主管部门
                                String competmentDepartment = tPoliciesDTO1.getCompetentDepartment();
                                // 申报日期
                                String startDateResult = tPoliciesDTO1.getStartDate();
                                if (startDateResult != null && !"".equals(startDateResult)) {
                                    startDateResult = startDateResult.split(" ")[0];
                                }
                                String endDateResult = tPoliciesDTO1.getEndDate();
                                if (endDateResult != null && !"".equals(endDateResult)) {
                                    endDateResult = endDateResult.split(" ")[0];
                                }
                                // 附件
                                List<Object> listAttachment = tPoliciesDTO1.getAttachment();


                                Integer fen = 0;
                                Integer yiClass = 0;
                                if (num_ip != null && !"".equals(num_ip) && num_ic != null && !"".equals(num_ic)) {
                                    yiClass = Integer.valueOf(num_ip) + Integer.valueOf(num_ic);
                                }
                                if (num_ntype != null && !"".equals(num_ntype) && num_out != null && !"".equals(num_out) && num_copyright != null && !"".equals(num_copyright)) {
                                    Integer twoClass = Integer.valueOf(num_ntype) + Integer.valueOf(num_out) + Integer.valueOf(num_copyright);
                                    if (yiClass >= 1 && twoClass > 6) {
                                        fen += 27;
                                    } else if (twoClass >= 6) {
                                        fen += 24;
                                    } else if (twoClass >= 4) {
                                        fen += 18;
                                    } else if (twoClass >= 3) {
                                        fen += 12;
                                    } else if (twoClass >= 2) {
                                        fen += 6;
                                    } else if (twoClass < 2) {
                                        fen += 0;
                                    }
                                }

//					    		rate_net_profit = "0.24";
                                Number m1 = null;
                                if (rate_net_profit != null && !"".equals(rate_net_profit)) {
                                    Double d1 = Double.parseDouble(rate_net_profit);
                                    String s1 = df.format(d1);
                                    // 净资产增长率
                                    m1 = df.parse(s1);
                                    Double doubleM1 = m1.doubleValue() * 100;
                                    int intValueM1 = doubleM1.intValue();
                                    if (intValueM1 >= 35) {
                                        fen += 10;
                                    } else if (intValueM1 >= 25) {
                                        fen += 8;
                                    } else if (intValueM1 >= 15) {
                                        fen += 6;
                                    } else if (intValueM1 >= 5) {
                                        fen += 4;
                                    } else if (intValueM1 >= 0) {
                                        fen += 2;
                                    } else if (intValueM1 < 0) {
                                        fen += 0;
                                    }
                                }


                                // 收入增长率
                                Number m2 = null;
                                if (rate_net_profit != null && !"".equals(rate_net_profit)) {
                                    Double d2 = Double.parseDouble(rate_income);
                                    String s2 = df.format(d2);
                                    m2 = df.parse(s2);
                                    Double doubleM1 = m2.doubleValue() * 100;
                                    int intValueM1 = doubleM1.intValue();
                                    // 收入增长率
                                    if (intValueM1 >= 35) {
                                        fen += 10;
                                    } else if (intValueM1 >= 25) {
                                        fen += 8;
                                    } else if (intValueM1 >= 15) {
                                        fen += 6;
                                    } else if (intValueM1 >= 5) {
                                        fen += 4;
                                    } else if (intValueM1 >= 0) {
                                        fen += 2;
                                    } else if (intValueM1 < 0) {
                                        fen += 0;
                                    }
                                }


                                TMatchingResultsDTOQuery tMatchingResultsQuery = new TMatchingResultsDTOQuery();
                                TMatchingResultsDTOUpdate tMatchingResultsUpdate = new TMatchingResultsDTOUpdate();
                                tMatchingResultsUpdate.setName(policiesId);
                                tMatchingResultsUpdate.setPolicystring(policiesName);
                                tMatchingResultsUpdate.setApplicationCondition(condition);
                                tMatchingResultsUpdate.setCompetentDepartment(competmentDepartment);
                                tMatchingResultsUpdate.setStartdate(startDateResult);
                                tMatchingResultsUpdate.setEnddate(endDateResult);
                                tMatchingResultsUpdate.setUrl(url);
                                tMatchingResultsUpdate.setApplicationDate(startDateResult + "-" + endDateResult);
                                tMatchingResultsUpdate.setAttachment(listAttachment);
                                tMatchingResultsUpdate.setMatchingDegree(new BigDecimal(fen));
                                tMatchingResultsUpdate.setUserInfo(corpName);

                                SaveOrUpdatetMatchingResultsDTO saveOrUpdatetMatchingResultsDTO1 = new SaveOrUpdatetMatchingResultsDTO();
                                //tMatchingResultsUpdate.setatsandboxDBId(ConstantExt._SAND_BOX_ID);
                                saveOrUpdatetMatchingResultsDTO1.setQuery(tMatchingResultsQuery);
                                saveOrUpdatetMatchingResultsDTO1.setUpdate(tMatchingResultsUpdate);
                                String message = tmatchingresultsApi.saveOrUpdatetMatchingResultsUsingPOST(saveOrUpdatetMatchingResultsDTO1).getMessage();
                                System.out.println("上海市高新技术企业入库培育: " + message);
                            }

                        } else {
                            System.out.println("快速匹配: 上海市高新技术企业入库培育 不满足必要条件");
                        }

                        // TODO 上海市专精特新中小企业认定  上海市科技小巨人企业认定
                        /**
                         * 专精特新增加对公司名称的判断
                         */
                        boolean isCopFlag = false;
                        if (StringUtils.isNotBlank(name)){
                            isCopFlag = name.contains("公司");
                        }
                        if (isweifa && isCopFlag) {
                            // 匹配政策
                            TPoliciesDTO tPoliciesQuery = new TPoliciesDTO();
                            tPoliciesQuery.setName("上海市专精特新中小企业认定");
                            //tPoliciesQuery.setatsandboxDBId(ConstantExt._SAND_BOX_ID);
                            List<TPoliciesDTOResponse> listPolicies = tpoliciesApi.findtPoliciesUsingPOST(tPoliciesQuery).getData();
                            if (listPolicies != null && listPolicies.size() > 0) {
                                TPoliciesDTOResponse tPoliciesDTO1 = listPolicies.get(0);
                                // 政策ID
                                String policiesId = tPoliciesDTO1.getId();
                                // 政策名称
                                String policiesName = tPoliciesDTO1.getName();
                                // 申报条件
                                String condition = tPoliciesDTO1.getCondition();
                                // 申报入口
                                String url = tPoliciesDTO1.getEntrance();
                                // 主管部门
                                String competmentDepartment = tPoliciesDTO1.getCompetentDepartment();
                                // 申报日期
                                String startDateResult = tPoliciesDTO1.getStartDate();
                                if (startDateResult != null && !"".equals(startDateResult)) {
                                    startDateResult = startDateResult.split(" ")[0];
                                }
                                String endDateResult = tPoliciesDTO1.getEndDate();
                                if (endDateResult != null && !"".equals(endDateResult)) {
                                    endDateResult = endDateResult.split(" ")[0];
                                }
                                // 附件
                                List<Object> listAttachment = tPoliciesDTO1.getAttachment();

                                Integer fen = 0;
                                // 资本2
                                if (assets != null && !"".equals(assets)) {
                                    BigDecimal assetsBigDecimal = new BigDecimal(assets);
                                    if (assetsBigDecimal.intValue() < 5000) {
                                        fen += 0;
                                    } else {
                                        fen += 1;
                                    }
                                }

                                // 去年营业收入
                                if (income != null && !"".equals(income)) {
                                    BigDecimal incomeBigDecimal = new BigDecimal(income);
                                    if (incomeBigDecimal.intValue() < 5000) {
                                        fen += 0;
                                    } else {
                                        fen += 3;
                                    }
                                }

                                if (income1 != null) {
                                    if (!"0".equals(income1)) {
                                        // 连续两年
                                        Integer inc = ((new BigDecimal(income).intValue() / new BigDecimal(income1).intValue()) ^ 1 / 2) * 100;
                                        if (inc <= 10) {
                                            fen += 5;
                                        } else if (inc > 10 && inc <= 20) {
                                            fen += 10;
                                        } else if (inc > 20 && inc <= 50) {
                                            fen += 15;
                                        } else if (inc > 50) {
                                            fen += 20;
                                        }
                                    }
                                }

                                // 专家判断
                                fen += 8;

                                TMatchingResultsDTOQuery tMatchingResultsQuery = new TMatchingResultsDTOQuery();
                                TMatchingResultsDTOUpdate tMatchingResultsUpdate = new TMatchingResultsDTOUpdate();
                                tMatchingResultsUpdate.setName(policiesId);
                                tMatchingResultsUpdate.setPolicystring(policiesName);
                                tMatchingResultsUpdate.setApplicationCondition(condition);
                                tMatchingResultsUpdate.setCompetentDepartment(competmentDepartment);
                                tMatchingResultsUpdate.setStartdate(startDateResult);
                                tMatchingResultsUpdate.setEnddate(endDateResult);
                                tMatchingResultsUpdate.setUrl(url);
                                tMatchingResultsUpdate.setApplicationDate(startDateResult + "-" + endDateResult);
                                tMatchingResultsUpdate.setAttachment(listAttachment);
                                tMatchingResultsUpdate.setMatchingDegree(new BigDecimal(fen));
                                tMatchingResultsUpdate.setUserInfo(corpName);

                                SaveOrUpdatetMatchingResultsDTO saveOrUpdatetMatchingResultsDTO1 = new SaveOrUpdatetMatchingResultsDTO();
                                //tMatchingResultsUpdate.setatsandboxDBId(ConstantExt._SAND_BOX_ID);
                                saveOrUpdatetMatchingResultsDTO1.setQuery(tMatchingResultsQuery);
                                saveOrUpdatetMatchingResultsDTO1.setUpdate(tMatchingResultsUpdate);
                                String message = tmatchingresultsApi.saveOrUpdatetMatchingResultsUsingPOST(saveOrUpdatetMatchingResultsDTO1).getMessage();
                                System.out.println("上海市专精特新中小企业认定: " + message);

                            }
                        } else {
                            System.out.println("快速匹配: 上海市专精特新中小企业认定 不满足必要条件");
                        }

                        // TODO 上海市科技小巨人企业认定
                        if ("1".equals(is_hightech)) {
                            if (isweifa) {
                                // 匹配政策
                                TPoliciesDTO tPoliciesQuery = new TPoliciesDTO();
                                tPoliciesQuery.setName("上海市科技小巨人企业认定");
                                //tPoliciesQuery.setatsandboxDBId(ConstantExt._SAND_BOX_ID);
                                List<TPoliciesDTOResponse> listPolicies = tpoliciesApi.findtPoliciesUsingPOST(tPoliciesQuery).getData();
                                if (listPolicies != null && listPolicies.size() > 0) {
                                    TPoliciesDTOResponse tPoliciesDTO1 = listPolicies.get(0);
                                    // 政策ID
                                    String policiesId = tPoliciesDTO1.getId();
                                    // 政策名称
                                    String policiesName = tPoliciesDTO1.getName();
                                    // 申报条件
                                    String condition = tPoliciesDTO1.getCondition();
                                    // 申报入口
                                    String url = tPoliciesDTO1.getEntrance();
                                    // 主管部门
                                    String competmentDepartment = tPoliciesDTO1.getCompetentDepartment();
                                    // 申报日期
                                    String startDateResult = tPoliciesDTO1.getStartDate();
                                    if (startDateResult != null && !"".equals(startDateResult)) {
                                        startDateResult = startDateResult.split(" ")[0];
                                    }
                                    String endDateResult = tPoliciesDTO1.getEndDate();
                                    if (endDateResult != null && !"".equals(endDateResult)) {
                                        endDateResult = endDateResult.split(" ")[0];
                                    }
                                    // 附件
                                    List<Object> listAttachment = tPoliciesDTO1.getAttachment();

                                    Integer fen = 0;

//						    		// 负债率
                                    Number m1 = null;
                                    if (rate_net_profit != null && !"".equals(rate_net_profit)) {
                                        Double d1 = Double.parseDouble(rate_net_profit);
                                        String s1 = df.format(d1);
                                        // 净资产增长率
                                        m1 = df.parse(s1);
                                        Double doubleM1 = m1.doubleValue() * 100;
                                        int intValueM1 = doubleM1.intValue();
                                        if (intValueM1 >= -70) {
                                            fen += 10;
                                        }
                                    }
//					    			// 负债率 rate_ad
//					    			if(m3.intValue() <= 70) {
//					    				fen += 10;
//					    			}

                                    // 一类 二类
                                    Integer yiClass = 0;
                                    if (num_ip != null && !"".equals(num_ip) && num_ic != null && !"".equals(num_ic)) {
                                        yiClass = Integer.valueOf(num_ip) + Integer.valueOf(num_ic);
                                    }
                                    if (num_ntype != null && !"".equals(num_ntype) && num_out != null && !"".equals(num_out) && num_copyright != null && !"".equals(num_copyright)) {
                                        Integer twoClass = Integer.valueOf(num_ntype) + Integer.valueOf(num_out) + Integer.valueOf(num_copyright);
                                        if (yiClass >= 1 && twoClass > 6) {
                                            fen += 18;
                                        } else if (twoClass >= 6) {
                                            fen += 16;
                                        } else if (twoClass >= 4) {
                                            fen += 12;
                                        } else if (twoClass >= 3) {
                                            fen += 8;
                                        } else if (twoClass >= 2) {
                                            fen += 4;
                                        } else if (twoClass < 2) {
                                            fen += 0;
                                        }
                                    }

                                    TMatchingResultsDTOQuery tMatchingResultsQuery = new TMatchingResultsDTOQuery();
                                    TMatchingResultsDTOUpdate tMatchingResultsUpdate = new TMatchingResultsDTOUpdate();
                                    tMatchingResultsUpdate.setName(policiesId);
                                    tMatchingResultsUpdate.setPolicystring(policiesName);
                                    tMatchingResultsUpdate.setApplicationCondition(condition);
                                    tMatchingResultsUpdate.setCompetentDepartment(competmentDepartment);
                                    tMatchingResultsUpdate.setStartdate(startDateResult);
                                    tMatchingResultsUpdate.setEnddate(endDateResult);
                                    tMatchingResultsUpdate.setUrl(url);
                                    tMatchingResultsUpdate.setApplicationDate(startDateResult + "-" + endDateResult);
                                    tMatchingResultsUpdate.setAttachment(listAttachment);
                                    tMatchingResultsUpdate.setMatchingDegree(new BigDecimal(fen));
                                    tMatchingResultsUpdate.setUserInfo(corpName);

                                    SaveOrUpdatetMatchingResultsDTO saveOrUpdatetMatchingResultsDTO1 = new SaveOrUpdatetMatchingResultsDTO();
                                    //tMatchingResultsUpdate.setatsandboxDBId(ConstantExt._SAND_BOX_ID);
                                    saveOrUpdatetMatchingResultsDTO1.setQuery(tMatchingResultsQuery);
                                    saveOrUpdatetMatchingResultsDTO1.setUpdate(tMatchingResultsUpdate);
                                    String message = tmatchingresultsApi.saveOrUpdatetMatchingResultsUsingPOST(saveOrUpdatetMatchingResultsDTO1).getMessage();
                                    System.out.println("上海市科技小巨人企业认定: " + message);

                                }
                            }
                        } else {
                            System.out.println("快速匹配: 上海市科技小巨人企业认定 不满足必要条件");
                        }

                    }
                }
                serverResponse = ServerResponse.createSuccess("匹配成功");
            } else {
                serverResponse = ServerResponse.createError("匹配失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return serverResponse;
    }
}
